Facebook Pixel

Implement sum(1)(2)(3)(4)..(n) in JavaScript

The Amazon interview question: implement a curried sum function. Here is the solution.

Implement sum(1)(2)(3)(4)..(n) in JavaScript

This is a famous Amazon interview question. Here is how to implement it.

The Problem

sum(1)(2)(3)(4)(); // 10 sum(1)(2)(3); // function (can continue chaining)

Solution 1: Terminate with Empty Call

function sum(a) { return function (b) { if (b !== undefined) return sum(a + b); return a; }; } sum(1)(2)(3)(4)(); // 10

Each call returns a function. When called with no argument, it returns the accumulated sum.

Solution 2: Using toString

function sum(n) { const fn = (m) => sum(n + m); fn.toString = () => n; return fn; } sum(1)(2)(3) + 0; // 6 (JavaScript calls toString) console.log(sum(1)(2)(3)); // 6 (console.log calls toString)

Solution 3: Using valueOf

function sum(n) { const fn = (m) => sum(n + m); fn.valueOf = () => n; return fn; } Number(sum(1)(2)(3)); // 6

How It Works (Solution 1)

  1. sum(1) returns a function with a = 1.
  2. Calling it with 2 returns sum(1 + 2) = sum(3).
  3. Calling it with 3 returns sum(3 + 3) = sum(6).
  4. Calling it with 4 returns sum(6 + 4) = sum(10).
  5. Calling it with no argument () returns 10.

The Takeaway

sum(1)(2)(3)(4)..(n): each call returns a function that accumulates the sum. Terminate with an empty call (check b !== undefined) or use toString/valueOf for automatic conversion. This tests currying and closures.

function sum(a) { return function(b) { if (b !== undefined) return sum(a + b); return a; }; }. Each call returns a function that accumulates. Call with no argument to get the result: sum(1)(2)(3)().

Two approaches: (1) call with no argument: sum(1)(2)(3)() - check if b !== undefined. (2) toString override: sum(1)(2)(3) + 0 - JavaScript calls toString when arithmetic is performed.

Currying and closures. Each call returns a function that closes over the accumulated sum. Without closures, the inner function would not have access to the previous arguments.

function sum(n) { const fn = m => sum(n + m); fn.toString = () => n; return fn; }. When JavaScript needs a primitive (like + 0 or console.log), it calls toString and returns the accumulated sum.

Yes. Amazon asks candidates to implement a curried sum function that chains indefinitely. It tests understanding of currying, closures, function chaining, and JavaScript type coercion (if using toString).

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.