Skip to content
GreenSnippets

Curry a function

Turn a multi-argument function into one that can be called a few arguments at a time.

JavaScript
function curry(fn, arity = fn.length) {
  return function curried(...args) {
    return args.length >= arity
      ? fn.apply(this, args)
      : (...more) => curried.apply(this, [...args, ...more]);
  };
}

Example / expected output

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

How it works

The curried function collects arguments until it has as many as the original declares (fn.length), then calls it. Functions with default or rest parameters report a shorter length, so pass the arity explicitly for those.

  • JavaScript Tested

    Run a function only once

    Wrap a function so it executes on the first call and returns the same result afterwards.

  • JavaScript Tested

    Memoize a function

    Cache results by argument so expensive pure functions only run once per distinct input.

  • JavaScript Tested

    Compose and pipe functions

    Chain single-argument functions left-to-right with pipe, or right-to-left with compose.