Function Composition in JavaScript with Array.prototype.reduceRight

Functional programming in JavaScript has rocketed in popularity over the last few years. While a handful of its regularly-promoted tenets, such as immutability, require runtime workarounds, the language’s first-class treatment of functions has proven its support of composable code driven by this fundamental primitive. Before covering how one can dynamically compose functions from other functions, let’s take a brief step back.

What is a Function?

Effectively, a function is a procedure that allows one to perform a set of imperative steps to either perform side effects or to return a value. For example:

function getFullName(person) {
  return `${person.firstName} ${person.surname}`;
}

When this function is invoked with an object possessing firstName and lastName properties, getFullName will return a string containing the two corresponding values:

const character = {
  firstName: 'Homer',
  surname: 'Simpson',
};

const fullName = getFullName(character);

console.log(fullName); // => 'Homer Simpson'

It’s worth noting that, as of ES2015, JavaScript now supports arrow function syntax:

const getFullName = (person) => {
  return `${person.firstName} ${person.surname}`;
};

Given our getFullName function has an arity of one (i.e. a single argument) and a single return statement, we can streamline this expression:

const getFullName = person => `${person.firstName} ${person.surname}`;

These three expressions, despite differing in means, all reach the same end in:

  • creating a function with a name, accessible via the name property, of getFullName
  • accepting a sole parameter, person
  • returning a computed string of person.firstName and person.lastName, both being separated by a space

Combining Functions via Return Values

As well as assigning function return values to declarations (e.g. const person = getPerson();), we can use them to populate the parameters of other functions, or, generally speaking, to provide values wherever JavaScript permits them. Say we have respective functions which perform logging and sessionStorage side effects:

const log = arg => {
  console.log(arg);
  return arg;
};

const store = arg => {
  sessionStorage.setItem('state', JSON.stringify(arg));
  return arg;
};

const getPerson = id => id === 'homer'
  ? ({ firstName: 'Homer', surname: 'Simpson' })
  : {};

We can carry out these operations upon getPerson‘s return value with nested calls:

const person = store(log(getPerson('homer')));
// person.firstName === 'Homer' && person.surname === 'Simpson'; => true

Given the necessity of providing the required parameters to functions as they are called, the innermost functions will be invoked first. Thus, in the above example, getPerson‘s return value will be passed to log, and log‘s return value is forwarded to store. Building statements from combined function calls enables us to ultimately build complex algorithms from atomic building blocks, but nesting these invocations can become unwieldy; if we wanted to combine 10 functions, how would that look?

const f = x => g(h(i(j(k(l(m(n(o(p(x))))))))));

Fortunately, there’s an elegant, generic implementation we can use: reducing an array of functions into a higher-order function.

Accumulating Arrays with Array.prototype.reduce

The Array prototype’s reduce method takes an array instance and accumulates it into a single value. If we wish to total up an array of numbers, one could follow this approach:

const sum = numbers =>
  numbers.reduce((total, number) => total + number, 0);

sum([2, 3, 5, 7, 9]); // => 26

In this snippet, numbers.reduce takes two arguments: the callback which will be invoked upon each iteration, and the initial value which is passed to said callback’s total argument; the value returned from the callback will be passed to total on the next iteration. To break this down further by studying the above call to sum:

  • our callback will run 5 times
  • since we are providing an initial value, total will be 0 on the first call
  • the first call will return 0 + 2, resulting in total resolving to 2 on the second call
  • the result returned by this subsequent call, 2 + 3, will be provided to the total parameter on the third call etc.

While the callback accepts two additional arguments which respectively represent the current index and the array instance upon which Array.prototype.reduce was called, the leading two are the most critical, and are typically referred to as:

  • accumulator – the value returned from the callback upon the previous iteration. On the first iteration, this will resolve to the initial value or the first item in the array if one is not specified
  • currentValue – the current iteration’s array value; as it’s linear, this will progress from array[0] to array[array.length - 1] throughout the invocation of Array.prototype.reduce

Composing Functions with Array.prototype.reduce

Now that we understand how to reduce arrays into a single value, we can use this approach to combine existing functions into new functions:

const compose = (...funcs) =>
  initialArg => funcs.reduce((acc, func) => func(acc), initialArg);

Note that we’re using the rest params syntax (...) to coerce any number of arguments into an array, freeing the consumer from explicitly creating a new array instance for each call site. compose also returns another function, rendering compose a higher-order function, which accepts an initial value (initialArg). This is critical as we can consequently compose new, reusable functions without invoking them until necessary; this is known as lazy evaluation.

How do we therefore compose other functions into a single higher-order function?

const compose = (...funcs) =>
  initialArg => funcs.reduce((acc, func) => func(acc), initialArg);

const log = arg => {
  console.log(arg);
  return arg;
};

const store = key => arg => {
  sessionStorage.setItem(key, JSON.stringify(arg));
  return arg;
};

const getPerson = id => id === 'homer'
  ? ({ firstName: 'Homer', surname: 'Simpson' })
  : {};

const getPersonWithSideEffects = compose(
  getPerson,
  log,
  store('person'),
);

const person = getPersonWithSideEffects('homer');

In this code:

  • the person declaration will resolve to { firstName: 'Homer', surname: 'Simpson' }
  • the above representation of person will be output to the browser’s console
  • person will be serialised as JSON before being written to session storage under the person key

The Importance of Invocation Order

The ability to compose any number of functions with a composable utility keeps our code cleaner and better abstracted. However, there is an important point we can highlight by revisiting inline calls:

const g = x => x + 2;
const h = x => x / 2;
const i = x => x ** 2;

const fNested = x => g(h(i(x)));

One may find it natural to replicate this with our compose function:

const fComposed = compose(g, h, i);

In this case, why does fNested(4) === fComposed(4) resolve to false? You may remember my highlighting how inner calls are interpreted first, thus compose(g, h, i) is actually the equivalent of x => i(h(g(x))), thus fNested returns 10 while fComposed returns 9. We could simply reverse the invocation order of the nested or composed variant of f, but given that compose is designed to mirror the specificity of nested calls, we need a way of reducing the functions in right-to-left order; JavaScript fortunately provides this with Array.prototype.reduceRight:

const compose = (...funcs) =>
  initialArg => funcs.reduceRight((acc, func) => func(acc), initialArg);

With this implementation, fNested(4) and fComposed(4) both resolve to 10. However, our getPersonWithSideEffects function is now incorrectly defined; although we can reverse the order of the inner functions, there are cases where reading left to right can facilitate the mental parsing of procedural steps. It turns out our previous approach is already fairly common, but is typically known as piping:

const pipe = (...funcs) =>
  initialArg => funcs.reduce((acc, func) => func(acc), initialArg);

const getPersonWithSideEffects = pipe(
  getPerson,
  log,
  store('person'),
);

By using our pipe function, we will maintain the left-to-right ordering required by getPersonWithSideEffects. Piping has become a staple of RxJS for the reasons outlined; it’s arguably more intuitive to think of data flows within composed streams being manipulated by operators in this order.

Function Composition as an Alternative to Inheritance

We’ve already seen in the prior examples how one can infinitely combine functions into to larger, reusable, goal-orientated units. An additional benefit of function composition is to free oneself from the rigidity of inheritance graphs. Say we wish to reuse logging and storage behaviours based upon a hierarchy of classes; one may express this as follows:

class Storable {
  constructor(key) {
    this.key = key;
  }

  store() {
    sessionStorage.setItem(
      this.key,
      JSON.stringify({ ...this, key: undefined }),
    );
  }
}

class Loggable extends Storable {
  log() {
    console.log(this);
  }
}

class Person extends Loggable {
  constructor(firstName, lastName) {
    super('person');
    this.firstName = firstName;
    this.lastName = lastName;
  }

  debug() {
    this.log();
    this.store();
  }
}

The immediate issue with this code, besides its verbosity, is that we are abusing inheritance to achieve reuse; if another class extends Loggable, it is also inherently a subclass of Storable, even if we don’t require this logic. A potentially more catastrophic problem lies in naming collisions:

class State extends Storable {
  store() {
    return fetch('/api/store', {
      method: 'POST',
    });
  }
}

class MyState extends State {}

If we were to instantiate MyState and invoke its store method, we wouldn’t be invoking Storable‘s store method unless we add a call to super.store() within MyState.prototype.store, but this would then create a tight, brittle coupling between State and Storable. This can be mitigated with entity systems or the strategy pattern, as I have covered elsewhere, but despite inheritance’s strength of expressing a system’s wider taxonomy, function composition provides a flat, succinct means of sharing code which has no dependence upon method names.

Summary

JavaScript’s handling of functions as values, as well as the expressions which produce them, lends itself to the trivial composition of much larger, context-specific pieces of work. Treating this task as the accumulation of arrays of functions culls the need for imperative, nested calls, and the use of higher-order functions results in the separation of their definition and invocation. Additionally, we can free ourselves of the rigid hierarchical constraints imposed by object-orientated programming.

Sponsors