MediumFunctions📖 Theory Question

What is currying and how do you implement a generic curry function?

💡

Hint

Transform f(a,b,c) into f(a)(b)(c) — each call returns a new function waiting for more args

Full Answer

Currying transforms a multi-argument function into a chain of unary functions, each waiting for one argument at a time.

// Manual curried function
const add = a => b => c => a + b + c;
add(1)(2)(3); // 6
const add1 = add(1);     // partially applied — waits for b and c
const add1and2 = add1(2); // waits for c
add1and2(3);              // 6

// Generic curry utility
function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) { // enough args collected?
      return fn(...args);
    }
    return (...moreArgs) => curried(...args, ...moreArgs);
  };
}

const sum = (a, b, c) => a + b + c;
const curriedSum = curry(sum);
curriedSum(1)(2)(3); // 6
curriedSum(1, 2)(3); // 6 — also works (partial application hybrid)

Currying enables: partial application, point-free style, composable specialized functions.

💡 Currying vs Partial Application: currying always breaks a function into unary steps. Partial application pre-fills SOME arguments and returns a function waiting for the rest.

More Functions Questions

EasyWhat is the difference between call, apply, and bind?EasyHow do arrow functions differ from regular functions?EasyWhat is a pure function and why does it matter?EasyWhat are Higher-Order Functions (HOF)?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint