Home >Web Front-end >JS Tutorial >How Can a Variadic Curried Sum Function in JavaScript Be Created Without Using the \' \' Babel Trick?

How Can a Variadic Curried Sum Function in JavaScript Be Created Without Using the \' \' Babel Trick?

DDD
DDDOriginal
2024-11-28 07:12:09373browse

How Can a Variadic Curried Sum Function in JavaScript Be Created Without Using the ' ' Babel Trick?

Variadic Curried Sum Without the Plus Babel Trick

Can JavaScript create a sum function that behaves like the following?

sum(1)(2) = 3
sum(1)(2)(3) = 6
sum(1)(2)(3)(4) = 10

It's mistakenly believed that this is impossible. However, it is feasible by leveraging the operator in combination with sum.

Solution:

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));

The key lies in the definition of valueOf and toString methods within the curried function. These methods dictate how the function behaves when coerced into a primitive value, such as a number. By returning n within these methods, we ensure that the curried function's internal state (the current sum) is preserved.

This technique enables the creation of a variadic curried sum function without relying on the babel trick.

The above is the detailed content of How Can a Variadic Curried Sum Function in JavaScript Be Created Without Using the \' \' Babel Trick?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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