How to make smart chaining of custom pure functions

I love the concept of the 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:

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):

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 unusually, 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 how this case can be written in the 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 reduce to this data but in a little bit unusual way. The statement above can be written like:

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
Front-end developer (London, UK). I ❤ React, Redux, lodash, React Storybook, and functional programming overall. Always open to learn 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: