How to make smart chaining of custom pure functions

Reading Time: 2 minutes

I love the concept of functional programming. Lately, in addition to my work with React + Redux +JS, etc. I have worked also a lot with the ClojureScript (I was warned that after I will start writing in any dialect of Clojure I will start thinking slightly different about functional programming, not I see that this is true).

Last weekends I was enjoying by doing some training tasks on JavaScript, and to solve one of the problems in it with the love of functional programming I came up with 4 pure functions (let’s name them function1, function2, function3, function4) that I wanted to apply to my data step by step to obtain the expected result. If it were a ClojureScript, the expected code should be something like this:
(def output-data (function4 (function3 (function2 (function1 input-data)))))
If to try to write something similar to this one in the JavaScript it should look like this (do not be confused with the different style of naming variables, it is caused by the language convention difference, not by anything else):
let outputData = function4(function3(function2(function4(inputData))));
If in the Clojure it is pretty much ok to have so many parentheses in one statement in the JavaScript it from my point of view looks a little bit unusual, less readable and I assume if we want to do something like this by 10+ functions it will begin to be ugly.

So, I was thinking of how this case can be written in a more readable way. Looking deeply and trying to understand what exactly happened with data in this process, I understood that we actually are trying to apply to reduce to this data but in a little bit unusual way. The statement above can be written like:
let outputData = [function1, function2, function3, function4]
.reduce((acc, step) => step(acc), inputData);

Now, for me, it looks more logical if we want to change now how the data is transformed we should just add/remove a pure function from the array of the modifiers, that will be applied to data.

Olena Sovyn
Senior Software Engineer (London, UK). I ❤ React, Redux, lodash, React Storybook, and functional programming overall. Always open for learning something new

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Spelling error report

The following text will be sent to our editors: