Function composition
Composing means combining simple functions to form a more complex one: the output of one is the input of the next.
const double = (n) => n * 2;
const increment = (n) => n + 1;
const doubleThenIncrement = (n) => increment(double(n));
console.log(doubleThenIncrement(5)); // 11
A generic compose function that applies from right to left:
const compose = (f, g) => (x) => f(g(x));
const result = compose(increment, double);
console.log(result(5)); // 11
Currying
Currying transforms a function of several arguments into a sequence of single-argument functions. It lets you "fix" parameters and create specialized functions:
const multiply = (a) => (b) => a * b;
const byThree = multiply(3); // fixes a = 3
console.log(byThree(5)); // 15
console.log(multiply(2)(4)); // 8
This relies on closures: the inner function "remembers" the value of a
even after the outer one has finished. Currying and composition are the
foundation for building reusable transformation pipelines.
Examples
Currying to create specialized functions
const add = (a) => (b) => a + b;
const add10 = add(10);
console.log(add10(5)); // 15
console.log(add(2)(3)); // 5