Coalescing a static set of items is easy:
var finalValue = configValue || "default"; # JavaScript
finalValue = configValue ? "default" # CoffeeScript
But is there a simple way to coalesce an array of unknown length? The simplest I could come up with was this (CoffeeScript):
coalesce = (args) -> args.reduce (arg) -> arg if arg?
coalesce [1, 2] # Prints 1
That's fine for simple lists, but
- ideally coalesceshould iterate overarguments, but it doesn't supportreduce, and
- if the array contains functions, you might want to return their return value rather than the functions themselves (this is my use case).
Based on Guffa's solution, here's a CoffeeScript version:
coalesce = (args) -> args[0]() ? coalesce args[1..]
Test in coffee:
fun1 = ->
  console.log 1
  null
fun2 = ->
  console.log 2
  2
fun3 = ->
  console.log 3
  3
coalesce [fun1, fun2, fun3]
Prints
1 # Log
2 # Log
2 # Return value
 
     
     
    