Function composition is the core of functional programming — combining simple functions to build complex transformations. compose runs right-to-left, pipe runs left-to-right. This article implements both and shows real-world transformation pipelines.
Prerequisites: Functions #2 — Currying
1. compose() — Right-to-Left
compose(f, g)(x) means f(g(x)) — apply g first, then f:
Loading editor...
2. pipe() — Left-to-Right (More Readable)
pipe(f, g)(x) means g(f(x)) — execution order matches reading order:
Loading editor...
3. Handling Multiple Arguments — Pipe with First Function
Loading editor...
4. Async Pipe — Chain Async Functions
Loading editor...
5. Pipe with Error Handling — Railway Pattern
Loading editor...
Key Takeaways
compose(f, g, h)(x)=f(g(h(x)))— right-to-left execution.pipe(f, g, h)(x)=h(g(f(x)))— left-to-right, reads in natural order.- Use
reduce/reduceRightfor the implementation — concise and correct. - Async pipe chains promise-returning functions sequentially.
- Safe pipe stops on error — the foundation of the Either monad and railway-oriented programming.
Next: FP #2 — transduce() — Map + Filter in One Pass — fuse map and filter into a single reduction for better performance.
