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
有帮助吗?

解决方案

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top