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');