And now we’ve arrived at the fun part and the inspiration for this article.

reduce is incredibly versatile and flexible! It can be used in a tonne of scenarios, it’s a damn shame that it’s mostly used to get the sum of numbers in an array or the “more advanced version” ( *sarcasm* ) in an array of objects get the sum of a certain property.

MDN! What’s your take on reduce? (Link)

Description:

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

Example:

const total = [0, 1, 2, 3].reduce((sum, value) => sum + value, 1); // total is 7

See that up there? The most common reduce example known to man and that wouldn’t be a problem if developers expanded on it rather than stopping there.

What I noticed happening with developers and reduce is that they either don’t need to sum up some numbers so they forget reduce exists or they remember reduce exists only when they need to sum up some numbers but ( as was implied before ) reduce can do so much more than just sum stuff.

The really cool thing about reduce is that it passes the result of one callback function invocation to the next one allowing us to do some crazy ass shenanigans like…

Compose Functions

The example for composing functions using reduce we’ll be looking at I jacked from Eric Elliott and his post about reducers, which I can’t recommend enough. Eric Elliott always produces quality content and you should definitely follow him on every possible platform!

The part that’s most interesting to us is this one:

const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);

That up there is poetry!

‘compose’ is partially applied ( curried ) with functions that will do their work and pass along the results to the next function in line, notice the usage of rest parameters so that we can compose as many functions as we want and all of them will be put in the ‘fns’ array. Baller!

Then we feed it the initial value ( x ) or rather the value on which you’ll apply actions — compose functions.

After that we reduceRight the array of gathered functions with the initial value — x, this is the same as reduce but starts at the end of the array and moves to the start because that is how ‘compose’ works if the opposite is more natural to you than you want to pipe functions.

Example usage:

const add1 = n => n + 1;

const double = n => n * 2; const add1ThenDouble = compose(

double,

add1

); add1ThenDouble(2); // 6

// ((2 + 1 = 3) * 2 = 6)