5. Implement curry(fn) — Currying in JavaScript

medium

Currying turns f(a, b, c) into f(a)(b)(c) — and any grouping in between. It's a closures-and-arity question dressed up as functional programming.

The idea

fn.length tells you how many arguments the function declares. Keep collecting arguments across calls until you have at least that many, then apply them all at once.

Two details that win points:

  1. fn.length is the arity — the key to knowing when to stop collecting.
  2. curried.apply(this, [...args, ...rest]) accumulates arguments while preserving this.

Follow-ups

  • "What about curried(1)(2)(3)()?" → arrow functions with rest params handle empty calls fine; discuss a placeholder API (curry.placeholder) if pushed.
  • "Infinite currying — sum(1)(2)(3)…()?" → return a function with a custom valueOf/toString that totals on coercion.

What to practice

Implement it, then extend to support placeholders so curried(_, 2)(1)(3) works.

More questions

index.js
function curry(fn) {
  // your code here
}

const sum = (a, b, c) => a + b + c;
const curried = curry(sum);
console.log(curried(1)(2)(3)); // 6
console.log(curried(1, 2)(3)); // 6

Tests

Test Code

Enter JavaScript that runs after your solution. It should return a value or a Promise.