javascript / intermediate
Snippet
Functional Pipe Composition
Pipe composition is a functional pattern where the output of one function becomes the input of the next. It allows you to build complex logic by combining simple, reusable functions in a readable top-to-bottom flow.
snippet.js
javascript
1
2
3
4
5
6
7
8
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);const getName = (person) => person.name;const uppercase = (str) => str.toUpperCase();const getGreeting = (name) => `Hello, ${name}!`;const welcomeMessage = pipe(getName, uppercase, getGreeting);console.log(welcomeMessage({ name: 'Markus' }));
Breakdown
1
const pipe = (...fns)
Uses the rest parameter syntax to collect an arbitrary number of functions into an array named 'fns'.
2
fns.reduce((v, f) => f(v), x)
Iterates through the functions, applying each to the result of the previous one, starting with the initial value 'x'.