CurryLoading saved progress…

Curry

Implement curry(fn), a function transformer that turns a multi-argument function into a chain of single-argument calls. Currying is a classic functional-programming technique named after Haskell Curry: instead of calling add(1, 2, 3) once with three arguments, you call add(1)(2)(3) three times with one argument each. Each intermediate call returns a new function waiting for the next argument; only when every parameter has been collected does the original function actually run.

Use the function's declared arity (fn.length) to decide when enough arguments have arrived. Once the arity is reached, invoke the original function with the accumulated arguments and return its result.

Signature

function curry<T>(fn: (...args: any[]) => T): (...args: any[]) => any;
// returns either another curried function (more args needed)
// or the result of fn (all args collected)

Examples

const sum = (a, b, c) => a + b + c;
const curried = curry(sum);

curried(1)(2)(3); // 6
curried(10)(20)(30); // 60
// Zero-arity functions invoke immediately.
const greet = () => 'hi';
curry(greet)(); // 'hi'

// Arity-1 functions need exactly one call.
const double = (x) => x * 2;
curry(double)(5); // 10

Notes

  • Strict single-arg. Each call to the returned curried function takes exactly one argument. curried(1, 2) is out of scope — that's the "loose curry" variant.
  • Arity from fn.length. Use fn.length to know how many arguments the original function declares. Rest parameters and default values affect length; assume the function uses only plain positional parameters.
  • Zero-arity is a special case. If fn.length === 0, calling curry(fn)() should invoke fn immediately and return its result.
  • No this binding required. Treat fn as a pure function; you don't need to preserve this through the chain.
  • Don't mutate. Each partial application should produce a fresh function. Calling curried(1) twice must yield two independent chains.
Loading editor…