标签:
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]);
callback
previousValue
initialValue
, if supplied. (See below.)currentValue
currentIndex
array
reduce
was called upon.initialValue
callback
.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 |
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
01 - Execise About Array.prototype.reduce()
标签:
原文地址:http://www.cnblogs.com/qq1105151861/p/5428705.html