Incrementally Summing Values with a Variadic Curried Function
Can we create a JavaScript function sum that behaves as follows?
sum(1)(2) = 3 sum(1)(2)(3) = 6 sum(1)(2)(3)(4) = 10
In a nutshell, the function should allow us to accumulate a sum by repeatedly passing in additional values.
Initially, we were told that such a function is impossible in JavaScript. However, an alternative approach emerged: adding a sign in front of the sum function.
+sum(1)(2)(3)(4)
The sign, when used in conjunction with a function, coerces the function's returned value to a number. So, in this case, the function sum is effectively returning numbers that are then incremented upon each subsequent call.
To achieve the desired behavior, we can employ a currying technique in our sum function. Here's how the implementation looks like:
function sum(n) { var v = function(x) { return sum(n + x); }; v.valueOf = v.toString = function() { return n; }; return v; } console.log(+sum(1)(2)(3)(4)); // Output: 10
This implementation wraps the sum function in the v variable, which is then returned. The v function allows us to incrementally add values to the n variable. By coercing v to a number using the operator, we can obtain the accumulated sum.
In the example, the console.log statement outputs 10, which is the sum of 1, 2, 3, and 4.
The above is the detailed content of How Can a Curried JavaScript Function Incrementally Sum Values?. For more information, please follow other related articles on the PHP Chinese website!