1

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

  1. ideally coalesce should iterate over arguments, but it doesn't support reduce, and
  2. 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

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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 );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.