Function Composition
suggest changeComposing multiple functions into one is a functional programming common practice;
composition makes a pipeline through which our data will transit and get modified simply working on the function-composition (just like snapping pieces of a track together)…
you start out with some single responsibility functions:
const capitalize = x => x.replace(/^\w/, m => m.toUpperCase());
const sign = x => x + ',\nmade with love';
and easily create a transformation track:
const formatText = compose(capitalize, sign); // left to right: capitalize, then sign
formatText('this is an example')
// This is an example,
// made with love
N.B. Composition is achieved through a utility function usually called compose as in our example.
Libraries disagree on the direction. Lodash flow and the function below apply left to right. Ramda compose applies right to left. This implementation is left to right:
const compose = (...funs) =>
x =>
funs.reduce((ac, f) => f(ac), x);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents