Typorithm · hard

Implement curry

curry-functioninterview-questionscurryclosureshigher-order
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Implement curry

0%

Implement It

curry(fn) returns a function that keeps collecting arguments across calls until it has at least fn.length of them, then invokes the original. A named inner curried closure checks args.length >= fn.length and otherwise returns a function that concatenates new args and recurses.

curry transforms a multi-argument function into one that can be called one argument (or a few) at a time. The key is fn.length, which reports how many parameters fn declares — the target arity.

The implementation returns a named inner function curried so it can refer to itself. Each call gathers the latest args; if args.length >= fn.length the original fn is invoked with all collected arguments via apply, preserving this.

If not enough arguments have arrived yet, curried returns another function that concatenates the freshly received args onto the previous ones and calls curried again. This recursion lets curry(add)(1)(2)(3), curry(add)(1, 2)(3), and curry(add)(1)(2, 3) all produce 6.

01

fn.length gives the target arity to compare against.

02

A named curried closure recurses until enough args arrive.

03

args.concat(more) accumulates arguments across calls.

function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) {
      return fn.apply(this, args);
    }
    return (...more) => curried.apply(this, args.concat(more));
  };
}

const add = (a, b, c) => a + b + c;
curry(add)(1)(2)(3);   // 6
curry(add)(1, 2)(3);   // 6
curry(add)(1)(2, 3);   // 6

Read the implementation

Connect each part of the code to the concept before you type.

1. Named inner function

curried is named so it can call itself recursively as more arguments arrive across calls.

return function curried(...args) {

2. Arity check

fn.length is the number of declared parameters; once enough args are collected, the original is invoked.

if (args.length >= fn.length) {

3. Invoke the original

When the arity is satisfied, call fn with the accumulated args and return its result.

return fn.apply(this, args);

4. Collect more args

Otherwise return a function that merges the new args with the old ones and recurses through curried.

return (...more) => curried.apply(this, args.concat(more));

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Implement curry: Lesson & Practice · Typorithm | ApplyDjinn