js关于reduce方法以及实现compose

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

上一篇:SSM-SpringMVC-12:SpringMVC中BeanNameViewResolver这种视图解析器


下一篇:.Net 5 调用 HttpContext.SignInAsync 报错 Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, string scheme, AuthenticationProperties properties) 解决