typestar

Currying and partial application in JavaScript

Fixing some arguments now and the rest later.

const scale = (factor) => (value) => value * factor;
const double = scale(2);

console.log(double(21), [1, 2, 3].map(scale(10)));

function format(prefix, unit, value) {
  return `${prefix}${value}${unit}`;
}

const asPercent = format.bind(null, "", "%");
console.log(asPercent(97.5));

const curry3 = (fn) => (a) => (b) => (c) => fn(a, b, c);
console.log(curry3(format)("~")("tpm")(104));

How it works

  1. A curried function takes one argument and returns a function.
  2. bind does partial application, and also fixes this.
  3. Argument order decides how reusable the partial is.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
387
Tokens
144
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 82 seconds.

Type this snippet

Step 2 of 5 in Composing functions, step 6 of 16 in Functions & patterns.

← Previous Next →