JavaScript: Lodash compose() and flow()

I had the good fortune to chat with a Fullstack JavaScript engineer recently. The subject was parsing and merging arrays of JSON based on a small set of rules. My first swing at the problem involved something that seems common for folks like myself who hail from a declarative programming background. Oh, the nested parens!

This engineer mentioned I could use chain() to make the code a bit easier to read and understand without having to find the inner function and start working backwards. In the same conversation the Lodash Functional Programming package was brought up, specifically the mention of using flow() to create a function pipeline to process the data.

The Lodash FP package includes dozens (if not perhaps all?) Lodash functions rewritten to be curried. From a practical perspective the most striking difference is argument order. Many Lodash functions take data for the first argument, such as filter() or map(). The function variants in the FP package have changed this order so data is the last argument, which is required for using something like flow() or compose().

A great deal of information is available on the specifics of flow() and compose() in the form of videos, tutorials and such, all quite googlable.

In order to put some of that information to work I created a small exercise for myself. The problem; generate a list of user objects from an array of user names. The user objects contain a hash of the username…for no reason other than to do it, and an email address. Nothing fancy.

Here we create a an array of functions we’d like to apply to the our data. Each function’s output will be fed into the next function’s input. So long as you ensure you are type-correct then this makes creating a pipeline of function calls quite easy!

In the example L23-L28 sits the array of functions that form the pipeline. As you can see, the first thing we do is sort the list then map over the list to create an array of objects. From there we build on the objects in the array with each subsequent function call, adding the hash then email address.

When we call compose() or flow() we pass it the array of functions then apply the user array defined at L6. Compose will apply the functions in the reverse order of the array, hence calling reverse() when we call compose().

Like what you read? Give Jason Child a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.