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)
}
}
网友评论