JavaScript Functions Function Composition

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Composing 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:

6
 const capitalize = x => x.replace(/^\w/, m => m.toUpperCase());
 const sign = x => x + ',\nmade with love';

and easily create a transformation track:

6
 const formatText = compose(capitalize, 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.

Implementation of compose are present in many JavaScript utility libraries (lodash, rambda, etc.) but you can also start out with a simple implementation such as:

6
 const compose = (...funs) =>
   x =>
   funs.reduce((ac, f) => f(ac), x);


Got any JavaScript Question?