Facebook Pixel

Currying Interview Questions in JavaScript

Common currying interview questions including the Amazon sum(1)(2)(3) question.

Currying Interview Questions

Q1: Implement sum(1)(2)(3)()

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

Q2: Implement sum(1)(2)(3)(4)..(n) (Amazon)

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

Or with toString:

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

Q3: Implement a generic curry function

function curry(fn) { return function curried(...args) { if (args.length >= fn.length) return fn(...args); return (...next) => curried(...args, ...next); }; }

Q4: What is the difference between currying and partial application?

Currying: f(a)(b)(c) (one at a time). Partial: f(a, b) with c preset (some at once).

The Takeaway

Interview questions: sum(1)(2)(3)() (recursive with termination), sum(1)(2)(3)(4)..(n) (Amazon, same pattern), generic curry (recursive with fn.length check), and the difference between currying and partial application.

function sum(a) { return function(b) { if (b !== undefined) return sum(a + b); return a; }; }. Call with no argument to terminate and return the accumulated sum.

Same pattern: function sum(a) { return function(b) { if (b !== undefined) return sum(a + b); return a; }; }. Or use toString: function sum(n) { const fn = m => sum(n + m); fn.toString = () => n; return fn; }.

function curry(fn) { return function curried(...args) { if (args.length >= fn.length) return fn(...args); return (...next) => curried(...args, ...next); }; }.

Currying transforms f(a, b, c) into f(a)(b)(c) - one argument at a time. Partial application presets some arguments and returns a function for the rest: f'(b, c) with a preset.

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.

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