문제

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