Functional composition applies one function to the results of another: const f = x => g(h(x)). In the example functions g and h are composed. In Haskell notation it can be rewritten as follows: f = g . h, where . is an infix compose function.

It is ok to have just one nested pair of parentheses in your code, but when you need to compose multiple functions it is better to use a higher-order function like Ramda’s compose. I prefer to write it line by line with trailing comma:

import R from 'ramda';

const f = R.compose(
  g,
  h,
  m,
  n,
  p,
)

This code is equivalent to the following less readable and modifiable code:

const f = x => g(h(m(n(p(x)))))

What if we can compose functions in JS like in Haskell:

const f = g . h . m . n . p;

It looks concise, easy to read, fast to write. The best part is that it’s possible in JS.

#functional-programming #haskell #js #javascript

Haskell-like Composition in JavaScript
4.85 GEEK