Composition With Javascript
A composition in functional programming is a function that has been ‘composed’ from two functions.
More formally a composition is when we have a function f that
takes an argument of type A and returns B
(A → B) and another function g that takes an
argument of type B and returns C (B → C).
Then we can create a function out of f and g that takes
an argument of type A and returns C
(A → C).
This type of function composition can be denoted as f ∘ g.
Below is an implementation of a compose function in JavaScript (note! the functions are applied in a left to right order).
Composing multiple functions
In practice a more useful compose function would allow you to compose a variadic amount of functions at the same time.
When composing multiple functions it’s good to realise that function
composition is always associative. Which means that
f ∘ (g ∘ h) gives the same result as
(f ∘ g) ∘ h.
Below is an implementation in JavaScript that composes together a variadic amount of functions.