函数柯里化

1,固定参数的柯里化

function add(a, b, c, d) {
    return a + b + c + d;
}
function FixedParamsCurry(fn) {
    //arguments:[add,1]
    var args = arguments;
    var _arg = [].slice.call(args, 1);//[1]
    return function () {
        //arguments:[2,3,4]
        var newArg = _arg.concat([].slice.call(arguments, 0));//[1,2,3,4]
        return fn.apply(this, newArg);
    }
}
// var newAdd = FixedParamsCurry(add, 1);
// console.log(newAdd(2, 3, 4));

2,真正的柯里化 期望下次凑齐参数

function Curry(fn, length) {
    var length = length || fn.length;

    return function () {
        if (arguments.length < length) {
            //[fn,1]
            var combined = [fn].concat([].slice.call(arguments, 0));
            return Curry(FixedParamsCurry.apply(this, combined), length - arguments.length);
        } else {
            return fn.apply(this, arguments);
        }
    }
}
var newAdd = Curry(add);
console.log(newAdd(1, 2, 3, 4));
console.log(newAdd(1)(2, 3)(4));
console.log(newAdd(1, 2)(3, 4));

var na1 = newAdd(1);
var na2 = na1(2);
console.log(na2(4,4,));

3,应用柯里化

//post www.test1.com 'name=cst&cost=111'
//post www.test1.com 'key=111'
//post www.test2.com 'name=cst&cost=222'
//post www.test2.com 'key=222'
function ajax(method,url,data){
    console.log(method,url,data);
}
// ajax('POST',"www.test1.com",'name=cst&cost=111');
// ajax('POST',"www.test1.com",'key=111');
// ajax('POST',"www.test2.com",'name=cst&cost=222');
// ajax('POST',"www.test2.com",'key=222');

var ajaxCurry = Curry(ajax);
var postAjax = ajaxCurry('POST');

var postTest1Ajax = postAjax("www.test1.com");
postTest1Ajax('name=cst&cost=111');
postTest1Ajax('key=111');

var postTest2Ajax = postAjax("www.test2.com");
postTest2Ajax('name=cst&cost=222');
postTest2Ajax('key=111');
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值