码迷,mamicode.com
首页 > 其他好文 > 详细

01 - Execise About Array.prototype.reduce()

时间:2016-04-24 23:04:19      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:

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

callback
Function to execute on each value in the array, taking four arguments:
previousValue
The value previously returned in the last invocation of the callback, or initialValue, if supplied. (See below.)
currentValue
The current element being processed in the array.
currentIndex
The index of the current element being processed in the array.
array
The array reduce was called upon.
initialValue
Optional. Value to use as the first argument to the first call of the 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

Array.protot

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

 

 previousValuecurrentValuecurrentIndexarrayreturn 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

ype.re[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) { return previousValue + currentValue; }, 10);

 

Array.prototype

 

 

01 - Execise About Array.prototype.reduce()

标签:

原文地址:http://www.cnblogs.com/qq1105151861/p/5428705.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!