Solving sum with a Generic Curry Function
How to solve the sum question using a generic curry approach.
Solving sum with a Generic Curry Function
The Generic Approach
function curry(fn) { return function curried(...args) { if (args.length >= fn.length) return fn(...args); return (...next) => curried(...args, ...next); }; } const add = curry((a, b) => a + b); add(1)(2); // 3 add(1, 2); // 3
For the Amazon Question
The Amazon question is slightly different: it allows infinite chaining (not a fixed number of arguments). So the generic curry does not directly apply, but the concept does.
Adapting for Infinite Chaining
function infiniteCurry(fn, initial) { return function curried(...args) { if (args.length === 0) return initial; return infiniteCurry(fn, fn(initial, ...args)); }; } const sum = infiniteCurry((a, b) => a + b, 0); sum(1)(2)(3)(); // 6
The Takeaway
Generic curry: collects arguments until enough are gathered, then calls the original. For the Amazon question (infinite chaining), adapt the curry to terminate on empty call. The concept (closures, accumulation) is the same.
The standard generic curry does not directly apply (it expects a fixed number of arguments). But you can adapt it for infinite chaining: function infiniteCurry(fn, initial) { return function(...args) { if (args.length === 0) return initial; return infiniteCurry(fn, fn(initial, ...args)); }; }
Generic curry expects a fixed number of arguments (fn.length) and calls the original when enough are collected. The Amazon sum allows infinite chaining and terminates on an empty call. The concept (closures, accumulation) is the same but the termination mechanism differs.
Instead of checking args.length >= fn.length, check if no arguments were passed (args.length === 0). If so, return the accumulated value. Otherwise, return a new curried function with the updated accumulator.
fn.length is the number of parameters declared in the original function. The curry function uses it to know when enough arguments have been collected. For (a, b) => a + b, fn.length is 2.
It is a variation. Standard currying has a fixed number of arguments. The Amazon question allows infinite chaining with a custom termination (empty call or toString). It tests the same concepts (closures, function chaining) but requires a different termination mechanism.
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.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

