// 函数柯里化 将多个参数的函数 转换为 一个参数函数的方法
function mycurry(fn, beforeRoundArg = []) {
return function () {
let args = [...beforeRoundArg, ...arguments];
if (args.length < fn.length) {
return mycurry.call(this, fn, args);
} else {
return fn.apply(this, args);
}
};
}
function sum(a, b, c) {
return a + b + c;
}
let sumFn = mycurry(sum);
console.log(sumFn(1)(2)(3)); //6
console.log(sumFn(1)(2,4)); //7
// 函数柯里化实现2
function curry(fn){
return function curried(...args){
if(args.length >= fn.length){
return fn.apply(this,args);
}else{
return function(...ARGS){
console.log(ARGS);
return curried.apply(this,args.concat(ARGS));
}
}
}
}
function add(a,b,c){
return a+b+c
}
const curriedAdd = curry(add)
console.log(curriedAdd(2)(3)(9)); //14