javascript / expert
Snippet
Function Composition via Pipe Combinators
Pipe is a functional programming pattern that composes multiple functions into a single transformation pipeline. It improves readability by allowing data to flow from left to right, avoiding deeply nested function calls and reducing imperative boilerplate.
snippet.js
1
2
3
4
5
6
7
8
9
const pipe = (...fns) => (initialValue) =>fns.reduce((acc, fn) => fn(acc), initialValue);const normalize = s => s.trim().toLowerCase();const slugify = s => s.replace(/\s+/g, '-');const label = s => `id:${s}`;const createSlug = pipe(normalize, slugify, label);console.log(createSlug(' Expert JS Snippet ')); // 'id:expert-js-snippet'
Breakdown
1
fns.reduce((acc, fn) => fn(acc), initialValue)
Sequentially applies each function in the array to the accumulated result.
2
const createSlug = pipe(...)
Creates a new reusable function by composing smaller, specialized functions.