javascript / intermediate
Snippet
Function Composition (Pipe)
Function composition is the process of combining two or more functions to produce a new function. A 'pipe' flows data through a sequence of functions from left to right.
snippet.js
javascript
1
2
3
4
5
6
const double = x => x * 2;const addTen = x => x + 10;const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);const processNumber = pipe(double, addTen);console.log(processNumber(5)); // (5 * 2) + 10 = 20
Breakdown
1
(...fns) =>
Uses rest parameters to collect any number of functions into an array.
2
(x) =>
Returns a function that takes the initial value to be processed.
3
fns.reduce((v, f) => f(v), x);
Iteratively applies each function to the result of the previous one, starting with 'x'.
4
pipe(double, addTen);
Creates a new function that represents the sequence of operations.