/** 冴羽-专题系列目录-JavaScript专题之函数柯里化
function sub_curry(fn) {
var args = [].slice.call(arguments, 1);
return function() {
return fn.apply(this, args.concat([].slice.call(arguments)));
};
}
function curry(fn, length) {
length = length || fn.length;
var slice = Array.prototype.slice;
return function() {
if (arguments.length < length) {
var combined = [fn].concat(slice.call(arguments));
return curry(sub_curry.apply(this, combined), length - arguments.length);
} else {
return fn.apply(this, arguments);
}
};
}
*/
function curry(fun, ...rest) {
let argsLength = fun.length
return function(...args) {
let allArgs = rest.concat(args)
if (allArgs.length >= argsLength) {
return fun.apply(this, allArgs)
} else {
return curry.apply(this, [fun].concat(allArgs))
}
}
}
let testFun = function(a, b, c, d) {
return [a, b, c, d]
}
let curryTestFun = curry(testFun)
// console.log(curryTestFun(1, 2, 3, 4))
// console.log(curryTestFun(1)(2)(3)(4))
// console.log(curryTestFun(1)(3, 2)(3))
let curryTestFun1 = curryTestFun(3)
console.log(curryTestFun1(2, 3, 4))
console.log(curryTestFun1(3)(6, 4))
let curryTestFun2 = curry(testFun, 10)
console.log(curryTestFun2(3)(6, 4))
console