我有下面的代码,其中,我包装了函数来实现上述行为。但不幸的是,只有当参数数量等于2时,它才会返回预期结果。
function baseCurry (func) {
return function (...args) {
if (args.length >= func.length) {
return func.call(this, ...args)
} else {
return baseCurry(func.bind(this, ...args))
}
}
}
function addHelper (x, y) {
return x + y;
}
const superCurry = baseCurry(addHelper);
测试用例:
console.log(superCurry(1, 5)); // 6
console.log(superCurry(1)(5)); // 6
console.log(superCurry(1)); // [Function (anonymous)]
console.log(superCurry(1)(2)(3)); // Error
console.log(superCurry(1,2)(3)); // Error
我需要对其进行更改,使其给出所有n >= 1
的预期结果,其中"n"是参数的数量
注意:
参数可以以任何组合传递,如
console.log(superCurry(1,2)(3)(4))
console.log(superCurry(1,2,3)(5,7)(4)(8,9))
提前感谢
我可以做一些与您预期类似的事情,但我确实需要在调用链的末尾添加一对()
,以便function
知道何时返回function
以及何时返回值。
function baseCurry (func, value) {
this.value = value ?? 0;
return (...args) => {
if (args.length === 0) {
let val = this.value;
this.value = 0;
return val;
}
for (let index = 0; index < args.length; index += func.length - 1) {
this.value = func(this.value, ...args.slice(index, (index + func.length - 1 <= args.length) ? index + func.length - 1 : undefined));
}
return baseCurry(func, this.value);
}
}
function addHelper (x, y) {
return x + y;
}
const superCurry = baseCurry(addHelper);
console.log(superCurry(1, 5)());
console.log(superCurry(1)(5)());
console.log(superCurry(1)());
console.log(superCurry(1)(2)(3)());
console.log(superCurry(1,2)(3)());
console.log(superCurry(1,2,3)());