RainZhai / rainzhai.github.com

宅鱼
http://rainzhai.github.io
Apache License 2.0
2 stars 0 forks source link

为什么使用柯里化函数 #23

Open RainZhai opened 5 years ago

RainZhai commented 5 years ago

这就是函数式的思想, 用已有的函数组合出新的函数, 而柯里化每消费一个参数, 都会返回一个新的部分配置的函数, 这为函数组合提供了更灵活的手段, 并且使得接口更为流畅. 常见作用: 1. 参数复用;2. 提前返回;3. 延迟计算/运行。

function curry(fn, args) {
    console.log(fn,args)
    var fnlen = fn.length;

    var args = args || [];

    return function() {

        var new_args = args.slice(0);

        allargs = new_args.concat([].slice.call(arguments))

        if (allargs.length < fnlen) {
            return curry.call(this, fn, allargs);
        }
        else {
            return fn.apply(this, allargs);
        }
    }
}

var fn = curry(function(a, b, c, d) {
    console.log([a, b, c, d]);
});

fn("a", "b", "c","d") 
//fn("a", "b")("c")('f') 
//fn("a")("b")("c")("c") 
//fn("a")("b", "c")("c")