Composable transformation pipelines
Quick answer
Function composition passes the result of one function to the next. A pipeline exposes transformation order and allows independent testing of each stage.
How it works
For unary functions, compose right-to-left as x => f(g(x)), or pipe left-to-right using (...fns) => x => fns.reduce((v,f)=>f(v),x). Empty pipe returns its input. Each stage must accept the preceding stage’s output. This synchronous implementation does not await promises; use an explicitly asynchronous design when stages are asynchronous.
const pipe=(...fs)=>x=>fs.reduce((v,f)=>f(v),x);const f=pipe(x=>x+2,x=>x*3);console.log(f(4),pipe()(4));Expected output in Node.js:
18 4Left-to-right composition applies addition before multiplication.
const clean=s=>s.trim();const label=s=>"id:"+s.toLowerCase();console.log(label(clean(" A ")));Expected output in Node.js:
id:aThe cleaning stage supplies the input to the label stage.
Common mistakes
Order matters: trim before parsing or normalization before comparison when appropriate. Do not mix asynchronous functions into a synchronous pipe without handling promises.
Practice
Create trim, lower-case and prefix stages and test the pipeline with empty and mixed-case strings.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Composable transformation pipelines — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
In pipe(addTwo, triple), which operation runs first?
What should a unary empty pipe return?
Can this synchronous reduce pipe automatically await promises?
What is the exact console output in Composable transformation pipelines example 1?
const pipe=(...fs)=>x=>fs.reduce((v,f)=>f(v),x);const f=pipe(x=>x+2,x=>x*3);console.log(f(4),pipe()(4));What is the exact console output in Composable transformation pipelines example 2?
const clean=s=>s.trim();const label=s=>"id:"+s.toLowerCase();console.log(label(clean(" A ")));