← Back to libraryQuestion 167 of 468
🧩JavaScript CodingAdvanced

Curry a Function

📌 Definition:

Implement curry(fn) so that a function taking N arguments can be called as f(a)(b)(c) or f(a, b)(c) until all N are supplied.

📖 Detailed Explanation:

Track collected arguments; if enough have been gathered (>= fn.length), invoke the original; otherwise return a function that collects more. Currying enables partial application and reusable specialized functions.

💻 Solutions:
function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) return fn.apply(this, args);
    return (...next) => curried.apply(this, [...args, ...next]);
  };
}
// const add = curry((a, b, c) => a + b + c);
// add(1)(2)(3) === add(1, 2)(3) === 6
🔑 Key Points:
  • fn.length gives the expected argument count (arity)
  • Collect args until enough, then invoke
  • Enables partial application / reusable presets
  • Arrow default params reduce fn.length — watch out
🌍 Real-World Example:

Currying builds reusable, pre-configured helpers — e.g. a logger curried with a level, or an assertion curried with a fixed tolerance in a test framework.

🎯 Scenario-Based Interview Question:

curry stops working when the target function uses a default parameter, e.g. (a, b = 2) => a + b. Why?