Reputation: 58988
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
coalesce
should iterate over arguments
, but it doesn't support reduce
, andBased 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
Upvotes: 1
Views: 5478
Reputation: 109
This function works perfectly for me:
function coalesce(...param){
if (param.length == 0) return null;
return param.find(a => a !== null);
}
let value = coalesce(null, null, 1,2,3,4);
console.log('value = ', value );
Upvotes: 0
Reputation: 700880
You can do like this:
function coalesce(arr) {
if (arr.length == 0) return null;
var v = arr[0];
v = (typeof v == "function" ? v() : v);
return v | coalesce(arr.slice(1));
}
Example:
var finalValue = coalesce([ null, null, function(){ return null; }, 5 ]);
// finalValue is now 5
Upvotes: 3