compose 组合函数

254 阅读1分钟

compose 函数 以下将称之为组合

    var compose  = function(f,g){
        return function(x){
            return f(g(x))
        }
    }

fg 都是函数, x 是在它们之间通过管道传输的值。

组合 看起来像在饲养函数。 你就是饲养员, 选择两个有特点又遭你喜欢的函数, 让他们结合,产下一个崭新的函数。组合的用法如下:

    var toUpperCase = function(x) {
        return x.toUpperCase();
    }
    var exclaim = function(x){
     return x + "!"
    }
    var shout =  compose(exclaim, toUpperCase)
    shout("send in the clowns")
    
    // => "SEND IN THE CLOWNS!"

compose 的定义中, g 将先于 f 执行,因此就创建了一个从从右到左的数据流,这样做的可读性远远高于嵌套一大堆的函数调用, 如果不用组合, shout 函数将会是这样的。

    var shout = function(x){
        return exclaim(toUpperCase(x))
    }