码迷,mamicode.com
首页 > Web开发 > 详细

js关于reduce方法以及实现compose

时间:2021-05-24 16:04:18      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:text   ===   spec   ==   eve   type   ota   bsp   索引   

reduce语法

  array.reduce(function(total, currentValue, currentIndex, arr), initialValue);

参数描述
total 必需。初始值, 或者计算结束后的返回值。
currentValue 必需。当前元素
currentIndex 可选。当前元素的索引
arr 可选。当前元素所属的数组对象。

 

例子:

var params1 = [‘key1‘,‘key2‘,‘key3‘];
  //true 为初始值,即第一次执行reduce时flag的值,return item+1返回的是下一次reduce的flag值
function paramsValidate(params) {
  eturn params.reduce((flag, item) => { return item+1 }, true);
  //三次执行的过程
  //(true, ‘key1‘) => { return ‘key1‘+1 }
  //(‘key11‘, ‘key2‘) => { return ‘key2‘+1 }
  //(‘key21‘, ‘key3‘) => { return ‘key3‘+1 }
}

 

使用reduce实现compose方法:

function compose(...funs) {
  return (args) => {
    if (funs.length === 0) {
      return args;
    }
    if (funs.length === 1) {
      return funs[0](args);
    }

    //reverse()反转funs数组,是为了从fun3开始执行,如果想从fun1开始执行,reverse()可以去掉;
    return funs.reverse().reduce((x,y)=>{
      return typeof x == ‘function‘? y(x(args)):y(x);
    });
  }
}
compose(fun1,fun2,fun3)(value);
//执行结果等于fun1(fun2(fun3(value)));
//(fun1,fun2,fun3)为参数...funs,value为参数args

 

js关于reduce方法以及实现compose

标签:text   ===   spec   ==   eve   type   ota   bsp   索引   

原文地址:https://www.cnblogs.com/wen-web/p/14784361.html

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