// 题目:
const add = (x, y = 1) => x + y;
const mul = x => x * 3;
const div = x => x / 2;
// console.log(div(mul(add(3, 1))))
// 代码阅读性差
// 我们希望的调用方式:compose(add, mul, div)(3, 1)
function compose(...funcs) {
return function(...args) {
if(funcs.length === 0) return args;
if(funcs.length === 1) return funcs[0](...args);
return funcs.reduce((a, b, currentIndex) => {
if (currentIndex === 1) {
return b(a(...args))
} else {
return b(a)
}
})
}
}
// let compose = (...funcs) => (...args) => {
// if ...
// }
console.log('从左往右', compose(add, mul, div)(3, 1))
// 从后往前执行
function compose2(...funcs) {
if (funcs.length === 0) {
return arg => arg
}
if (funcs.length === 1) {
return funcs[0]
}
return funcs.reduce((a, b) => (...args) => {
return a(b(...args))
})
}
console.log('从右往左', compose2(div, mul, add)(3))
// ==>> div(mul(add(4)))
console