Description:
Write a generic function chainer
Write a generic function chainer that takes a starting value, and an array of functions to execute on it (array of symbols for ruby).
The input for each function is the output of the previous function (except the first function, which takes the starting value as it's input). Return the final value after execution is complete.
1 function add(num) { 2 return num + 1 3 } 4 5 function mult(num) { 6 return num * 30 7 } 8 9 chain(2, [add, mult]);10 // returns 90;
我的答案是:
function chain(input, fs) { var result = input; for(var i = 0; i < fs.length; i++) { result = fs[i](result); } return result;}
最优解是:
function chain(v, fns) { return fns.reduce(function(v, fn) { return fn(v) }, v);}
然后引发了对reduce方法的关注,在MDN中
Array.prototype.reduce()的语法如下:arr.reduce(callback[,initialValue]);
- Function to execute on each value in the array, taking four arguments:
- The value previously returned in the last invocation of the callback, or
initialValue
, if supplied. (See below.) - The current element being processed in the array.
- The index of the current element being processed in the array.
- The array
reduce
was called upon.
previousValue
currentValue
currentIndex
array
- The value previously returned in the last invocation of the callback, or
- Optional. Value to use as the first argument to the first call of the
callback
.
callback
initialValue
Example:
[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) { return previousValue + currentValue;});
The callback would be invoked four times, with the arguments and return values in each call being as follows:
previousValue | currentValue | currentIndex | arr | return value | |
first call | 0 | 1 | 1 | [0, 1, 2, 3, 4] | 1 |
second call | 1 | 2 | 2 | [0, 1, 2, 3, 4] | 3 |
third call | 2 | 3 | 3 | [0, 1, 2, 3, 4] | 6 |
fourth call | 6 | 4 | 4 | [0, 1, 2, 3, 4] | 10 |
If you were to provide an initial value as the second argument to reduce
, the result would look like this:
[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) { return previousValue + currentValue;}, 10);
previousValue | currentValue | currentIndex | array | return value | |
---|---|---|---|---|---|
first call | 10 | 0 | 0 | [0, 1, 2, 3, 4] | 10 |
second call | 10 | 1 | 1 | [0, 1, 2, 3, 4] | 11 |
third call | 11 | 2 | 2 | [0, 1, 2, 3, 4] | 13 |
fourth call | 13 | 3 | 3 | [0, 1, 2, 3, 4] | 16 |
fifth call | 16 | 4 | 4 | [0, 1, 2, 3, 4] | 20 |
The final call return value (20
) is returned as a result of the reduce function.