pipe, compose - 2023-02-17

2023-02-16  本文已影响0人  勇敢的小拽马
const add = x => x + 10;
const multiply = x => x * 10;
 
// 我们的计算改为两个函数的嵌套计算,add函数的返回值作为multiply函数的参数
let res = multiply(add(10));
console.log(res);    // 结果还是200
// 先加再乘
// let calculate = pipe(add, multiply);
// 左 -> 右
const pipe = (...funs) => {
  return function(x) {
    return funs.reduce((res, fun) => {
      return fun(res)
    }, x)
  }
}

// let calculate = compose(multiply, add);
// 右 -> 左
const compose = (...funs) => {
  return function(x) {
    funs.reduceRight((res, fun) => {
      return fun(res)
    }, x)
  }
}
上一篇 下一篇

猜你喜欢

热点阅读