美文网首页
pipe, compose - 2023-02-17

pipe, compose - 2023-02-17

作者: 勇敢的小拽马 | 来源:发表于2023-02-16 12:34 被阅读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)
  }
}

相关文章

网友评论

      本文标题:pipe, compose - 2023-02-17

      本文链接:https://www.haomeiwen.com/subject/pjspkdtx.html