function fn1(x) {
return x + 10
}
function fn2(x) {
return x * 3
}
function fn3(x) {
return x % 10
}
console.log(fn3(fn2(fn1(5)))) // 5
// 函数扁平化
function compose(...funcs) { // funcs:传递的函数(type: function)
return function proxy(...args) { // args: 传递的参数(type: Number)
const len = funcs.length
if (len === 0) return args // 没有传递函数
if (len === 1) return funcs[0](...args) // 执行一个函数,并把参数传递给该函数
return funcs.reduce((pre, cur) => {
return typeof pre === 'function' ? cur(pre(...args)) : cur(pre)
})
}
}
const com = compose(fn1, fn2, fn3)
console.log(com(5)) // 5
console.log(com(6)) // 8
JavaScript函数扁平化
最新推荐文章于 2022-07-16 21:33:04 发布