Skip to content

ducharm.dev

Simple Composition with Array.Reduce

Javascript1 min read

While looking at functional-php, I saw a pretty neat way of doing composition with an array_reduce method, and wanted to recreate it in JavaScript. There are plenty of libraries that implement this (and do so more effectively), but it's pretty fun knowing that you can get this functionality with a couple lines of plain JavaScript.

Here it is:

First, the spread operator here has the effect of accepting all the arguments as a single array, allowing us to use array methods on function's parameters.

So later, we won't have to pass an array of functions, and can just pass an arbitrary number of parameters:

Since the compose function must itself return a function, we need to pass a callback function to the reduce method that returns a function:

Previous will start as funcs[0] and current as funcs[1], but previous will accumulate each function in the array with each call of the callback function:

Once it's reached the end of the array, you have a function that contains calls to each function in the original array, with the very first function call containing your initial x. By returning functions that accept an x with each callback, you ensure that the x can be passed all the way back to the first function call.

For composition to work, the functions must all be unary (i.e. the must all take just one parameter). This is why curried functions are so useful - they make it much easier to compose functions together.

With compose, you can then create functions by simply stringing other functions together:

And also: if you prefer to have functions evaluated from right to left, you can use reduceRight instead: