JS手写代码之compose

函数调用的扁平化,即把层级嵌套的那种函数调用(一个函数的运行结果当作实参传给下一个函数的这种操作)扁平化,这就是compose函数。

function a (a) {
    return a
}
function b (a) {
    return a + 'b' 
}
function c (b) {
    return  b + 'c'
}

function compose(fns = []) {
    let len =  fns.length
    return function () {
        if(len === 0) return arguments
        if(len === 1) return fns[0].apply(this,arguments)
        let fn = fns.reduce((curr,next) => (...args) => curr(next(...args)))
       
        return fn.apply(this,arguments)
    }
}

let abc =  compose([c,b,a])('a')

console.log(abc); // 'abc'
posted @ 2021-07-28 14:09  有点油  阅读(242)  评论(0)    收藏  举报