柯里化学习
把函数变为接收一个参数,返回一个值得固定形式.
f(x,y,z)
-> f(x)(y)(z)
特性
1 匿名函数
2 每个函数只有一个输入参数
function currying(fn) {
var args = [].slice.call(arguments, 1);
return function() {
var newArgs = args.concat([].slice.call(arguments));
return fn.apply(null, newArgs);
}
}
var add = function(x,y) {
return x + y;
}
var result = curry(add, 5);
console.log(result(10));
function curryRight(fn) {
var args = [].slice.call(arguments, arguments.length -1 );
return function() {
var newArgs = [].concat([].slice.call(arguments), args);
return fn.apply(null, newArgs);
}
}
function curry(fn, length) {
// capture fn's # of parameters
length = length || fn.length;
return function () {
if (arguments.length < length) {
// not all arguments have been specified. Curry once more.
var combined = [fn].concat(toArray(arguments));
return length - arguments.length > 0
? curry(sub_curry.apply(this, combined), length - arguments.length)
: sub_curry.call(this, combined );
} else {
// all arguments have been specified, actually call function
return fn.apply(this, arguments);
}
};
}
var fn = curry(function(a, b, c) { return [a, b, c]; });
// these are all equivalent
fn("a", "b", "c");
fn("a", "b", "c");
fn("a", "b")("c");
fn("a")("b", "c");
fn("a")("b")("c");
//=> ["a", "b", "c"]