https://juejin.cn/post/6850418115042836487
https://blog.csdn.net/double_sweet1/article/details/122786636?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2
https://blog.csdn.net/qq_35083721/article/details/119736941
方式一:递归 + 函数自定义属性
function cumulative(a) {
let result = a ?? 0;
let sum = function (...args2) {
// 改造进行累加
result = result += args2.reduce((cur, prv) => (cur += prv), 0);
// 函数也是对象,可以给他添加属性
sum.result = result;
return sum;
};
// 怎么计算结果呢,args 里面存储着所有的值
return sum;
}
console.log(cumulative(1)); // fn
console.log(cumulative(1)(2)); // fn
console.log(cumulative(1)(2)(3)); // fn
console.log(cumulative(1)(2)(3)(4)); // fn
console.log(cumulative(1)(2)(3)(4)(5)); // fn
// ====>
const res = cumulative(1)(2)(3)(4)(5);
console.log(res.result); // 15
方式二:递归 + 类型转换
function cumulative(...args) {
let sum = function (...args2) {
// 将参数存储到一起
args.push(...args2);
return sum;
};
// 怎么计算结果呢,args 里面存储着所有的值, 重写 toString
sum.toString = function () {
return args.reduce((cur, pre) => (cur += pre), 0);
};
return sum;
}
console.log(cumulative(1));
console.log(cumulative(1)(2));
console.log(cumulative(1)(2)(3));
console.log(cumulative(1)(2)(3)(4));
console.log(cumulative(1)(2)(3)(4)(5));
// ===>
const res = cumulative(1)(2)(3)(4)(5);
console.log(parseInt("" + res)); // 15
方式三:
const add = (a, b, c) => a + b + c;
const curry = (fn) => {
let args = [];
//返回一个函数
return function temp(...newArgs) {
args.push(...newArgs); //储存数据
//数组长度和函数形参个数一致
if (args.length === fn.length) {
const val = fn.apply(this, args); //使用fn的方法添加数据
args = [];
return val; //返回最后添加的值
} else {
return temp;
}
};
};
const curryAdd = curry(add);
console.log(curryAdd(1)(2)(3)); // 6