Home > Web Front-end > JS Tutorial > How Can a Curried JavaScript Function Incrementally Sum Values?

How Can a Curried JavaScript Function Incrementally Sum Values?

Susan Sarandon
Release: 2024-11-28 14:48:16
Original
372 people have browsed it

How Can a Curried JavaScript Function Incrementally Sum Values?

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
Copy after login

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)
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template