compose 之递归实现
const add1 = (x) => x + 1
const mul3 = (x) => 3 * x
const div2 = (x) => x / 2
console.log(div2(mul3(add1(add1(0))))) // 3
console.log(div2(mul3(add1(add1(2))))) // 6
// 用递归实现
const compose = (...fns) => (param) => {
if (fns.length <= 1) {
return fns[0](param)
}
const fn = fns[0]
const restFns = fns.slice(1)
// compose(...restFns)(param) 这部分是一个整体
return fn(compose(...restFns)(param))
// 这种写法有问题...
// operate(0) operate(2)连续调用, 后面的值受到前面的值影响了 ?????
// const fn = fns.shift()
// return fn(compose(...fns)(param))
}
console.log(compose(div2, mul3, add1, add1)(0)) // 3
console.log(compose(div2, mul3, add1, add1)(2)) // 6
const operate = compose(div2, mul3, add1, add1)
console.log(operate(0)) // 3
console.log(operate(2)) // 6
compose 之 reduceRight 实现
const add1 = (x) => x + 1
const mul3 = (x) => 3 * x
const div2 = (x) => x / 2
console.log(div2(mul3(add1(add1(0))))) // 3
console.log(div2(mul3(add1(add1(2))))) // 6
// param是累加器(accumulator)的初始值
const compose = (...fns) => (param) => fns.reduceRight((acc, cur) => cur(acc), param)
console.log(compose(div2, mul3, add1, add1)(0)) // 3
console.log(compose(div2, mul3, add1, add1)(2)) // 6
const operate = compose(div2, mul3, add1, add1)
console.log(operate(0)) // 3
console.log(operate(2)) // 6
楼主残忍的关闭了评论