【发布时间】:2021-09-05 21:35:08
【问题描述】:
使用 ES5,如何 curry 一个接受无限参数的函数。
function add(a, b, c) {
return a + b + c;
}
上面的函数只接受三个参数,但我们希望我们的柯里化版本能够接受无限个参数。
因此,以下所有测试用例都应该通过:
var test = add(1);
test(2); //should return 3
test(2,3); //should return 6
test(4,5,6); //should return 16
这是我想出的解决方案:
function add(a, b, c) {
var args = Array.prototype.slice.call(arguments);
return function () {
var secondArgs = Array.prototype.slice.call(arguments);
var totalArguments = secondArgs.concat(args);
var sum = 0;
for (i = 0; i < totalArguments.length; i++) {
sum += totalArguments[0];
}
return sum;
}
}
但是,有人告诉我,它的风格不是很“实用”。
【问题讨论】:
-
您可能在第一个代码块中缺少
+:return a + b c;是指return a + b + c;? -
@unpollo ..typo 已修复
-
你为什么要这么做?
-
不过最好转到
haskell。 -
测试(2);使用您的代码时返回 4。 sum += totalArguments[0]; 0 应该是
i
标签: javascript functional-programming