The Compose Function

Learn about the compose function.

The use of higher-order functions is widespread in Redux applications, as it allows us to extend the behavior of other parts of the code easily. Take a look at an imaginary example where we have to wrap our original function in three wrappers:

const wrapped = third(second(first(originalFn)));

wrapped();

Using multiple decorators is a valid and practical approach, but the resulting code can be hard to read and appear somewhat cumbersome. Instead, Redux provides the compose() function to handle multiple wrappers more purely:

import { compose } from 'redux';

const wrapped = compose(third, second, first)(originalFn);

wrapped();

The simplest implementation of that function is elegant.

Notice: Using the reduceRight() method on the array of functions ensures that wrapping of higher-order functions happens from right to left.

This is the code from the redux library that essentially shows that compose works iteratively from the right of the arguments given to it. In contrast, the last argument is the original function.



function compose(...funcs) {
  return (...args) => {
    const last = funcs[funcs.length - 1]
    const rest = funcs.slice(0, -1)

    return rest.reduceRight(
      (composed, f) => f(composed),
      last(...args)
    )
  }
}

Get hands-on with 1200+ tech skills courses.