前言
有这样的一个需求:输入test(fun1, fun2, fun3...),要求按照fun1(fun2(fun3(...)))的顺序执行函数。
正文
其实这就是一个函数组合的问题
//函数组合
//需求:输入test(a,b,c,d,e,f....),执行a(b(c(d(e(f)))))
function compose () {
let argus = arguments
let start = arguments.length - 1
return function () {
let i = start
let result = argus[i].apply(null, arguments)
while (i--) {
result = argus[i].call(null, result)
}
return result
}
}
function a (x) {
console.log(x+1)
}
function b (x) {
return x * 2
}
let composefun = compose(a, b)
composefun(1)
网友评论