Facebook Pixel

sum(1)(2)(3) Variations and Follow-Up Questions

Variations of the sum question and follow-ups interviewers ask.

sum(1)(2)(3) Variations and Follow-Up Questions

Variation 1: sum(1)(2)(3)() - Empty Call Termination

function sum(a) { return function (b) { if (b !== undefined) return sum(a + b); return a; }; }

Variation 2: sum(1)(2)(3) + 0 - toString

function sum(n) { const fn = (m) => sum(n + m); fn.toString = () => n; return fn; }

Variation 3: sum(1, 2)(3)(4) - Mixed Arguments

function sum(...args) { const total = args.reduce((a, b) => a + b, 0); return function (b) { if (b !== undefined) return sum(total + b); return total; }; }

Follow-Up Questions

  1. "How would you support sum(1, 2)(3)?" - use rest params to accept multiple args.
  2. "How would you add multiplication?" - create a similar multiply function.
  3. "What if the chain is infinite?" - it already is; it only terminates when you call with no arg.
  4. "How would you convert this to a generic curry?" - use the generic curry function.

The Takeaway

Variations: empty call termination (if b !== undefined), toString (type coercion), mixed arguments (rest params). Follow-ups: support multiple args, add other operations, generic curry. Practice each variation.

Use rest parameters: function sum(...args) { const total = args.reduce((a, b) => a + b, 0); return function(b) { if (b !== undefined) return sum(total + b); return total; }; }.

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.

How would you support multiple arguments (rest params), add other operations (multiply, subtract), make it a generic curry function, and what is the time/space complexity.

Yes. The chain can continue indefinitely: sum(1)(2)(3)(4)(5)...(n). It only terminates when you call with no argument (or when JavaScript calls toString for type coercion). Each call creates a new function.

Use the generic curry function: function curry(fn) { return function curried(...args) { if (args.length >= fn.length) return fn(...args); return (...next) => curried(...args, ...next); }; }. Then const sum = curry((a, b) => a + b).

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.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.