你不知道的js之组合函数

组合函数:自己喜欢把他理解成复合函数,多个功能的调用。(对一个数据多次回调处理)

不废话,上代码

function compose(f, g) {
    return function (x) {
        return f(g(x))
    }
}
function toUp(str) {
    return str.toUpperCase()
}

function add(str) {
    return str + '!'
}
var p = compose1(add, toUp)
p('time')

想实现的功能为,‘time’ ==>‘TIME’ ==>‘TIME!’ ,通过变量p接收了compose的返回值(为一个函数f(x))函数的目的在于实现以上功能。

通过以上我们简单的了解了组合函数的目的,为此我们进行更深入的封装(当有多个功能需要使用时)

function compose() {
    var args = Array.prototype.slice.call(arguments)
    var len = args.length - 1
    return function (x) {
        var result = args[len](x);
        while (len--) {
            result = args[len](result)
        }
        return result
    }
}

以上代码能实现多个函数功能的复合使用。但是我们可以把程序变得更加完美,这里我们可以使用ES5的数组属性reduce

function compose1() {
    var args = Array.prototype.slice.call(arguments)
    var len = args.length - 1
    return function (x) {
        return args.reduceRight(function (res, cb) {
            return cb(res)
        }, x)
    }
}

如果你学过ES6,你会发现更加简单的写出以上代码

const compose2 = (...args) => x => args.reduceRight((res, cb) => cb(res), x)

未完待续。。。。。。

猜你喜欢

转载自blog.csdn.net/qq_35401191/article/details/82715235