#Closures#Currying

Infinite Curried Sum

sum(1)(2)(3) with no fixed arity — the running total appears when the result is coerced.

By Pratik RaiMedium

Write sum(n) so it can be called any number of times in a chain, each call adding to a running total.

The total appears when the result is converted to a primitive — by +, by String(), or inside a template literal. Two separate chains must not share a total.

Examples

Input:

JSfile.javascript
1+sum(1)(2)(3)

Output:

6

Each call adds to the closure's total; the unary + asks the returned function for its primitive value.

Constraints

  • Every argument is a number
  • Chains can be arbitrarily long

Notes

  • Unlike a fixed-arity curry, nothing tells the function when the chain has ended — coercion is the only signal.
  • A function is an object, and objects choose how they coerce.

Goal: Chain indefinitely, and produce the total on coercion.

Source

Frequently asked questions

How can a curried sum have no fixed number of calls?
Each call returns the same function with a larger running total, so the chain can go on indefinitely. Nothing signals the end — the total is read when the result is converted to a primitive.
What does valueOf do here?
It tells JavaScript what number this object becomes in a numeric context. `+sum(1)(2)` triggers it, which is how a function that always returns another function can still evaluate to `3`.
Why define toString as well?
Because string contexts — template literals, `String()` — ask for a string, not a number. Define only `valueOf` and those contexts fall back to `"[object Object]"`, which is the exact mistake reported in the interview this problem comes from.
How is this different from a normal curry?
A normal curry knows when to stop by comparing collected arguments against `fn.length`. An infinite chain has no arity to compare against, so coercion replaces the arity check entirely.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

Memoize

Cache a function by its arguments so the same call never computes twice.

JavaScript · ES6Pratik Rai ·

JavaScript

JS Output Challenges

Test your JavaScript skills by predicting console output for tricky code snippets. Covers hoisting, closures, this binding, async operations, and event loop quiz questions.

JavaScript · ES6Pratik Rai ·

JavaScript

Get smart in javascript

Level up your JavaScript expertise with advanced tips, tricks, and gotchas. Master closures, hoisting, coercion, and event loop behavior to write cleaner, bug-free code.

JavaScript · ES6Pratik Rai ·