March 13, 2015

Using Node.js to Code in a Functional Style

Node.js Software Development Startups Co-Building

Functional coding just makes sense. It’s not only fun, but it expedites your developing process. Coding in a more functional style improves code reliability, and simplifies the debugging and testing process. Thanks to composition possibilities, it’s possible to divide all transformations into separate functions, give them meaningful names, think over the signature, and provide proper coverage with testing. You’ll be surprised how much cleaner your code will become. Most importantly, functional coding presents new approaches to solving old problems.



Agreeing to Code Practically


Getting every developer on the team to agree on a different approach to coding will be challenge. Some will be hesitant, others may reject the idea. It will take time to get familiarized with new libraries, make changes in code-style and rules of the static code analyzer, and write several “how-to” wiki pages. The documentation is academic and laborious. Well, seriously, look at the function signature converge from ramda:



In addition, development speed may decrease in the beginning. Most developers will take a couple of seconds to figure out the code below:



…and way more time spent figuring out this:



It’s up to a team to figure out whether or not they want to take this new approach.



Using Familiar Tools


Lodash is used everywhere, but how many developers know that it has functional realization? Same functions but with the support for currying and composition. Let’s rewrite the following code:



using lodash-fp:



Let’s transform this code into a function and see how we can use it:



Currying and composition allowed us to integrate calculations into the chain of receiving and filtering data without problems. It should also be noted that the code has become much cleaner.


At the moment, many libraries for javascript implement similar functionality. Personally, I prefer Ramda due to null-values processing and convenient functions for working with Promise (pipeP и composeP):



In addition, ramda has an implementation Fantasy Land.



Introducing Fantasy Land


Fantasy Land is a formal specification of “algebraic structures” in JavaScript: monads, monoids, setoids, functors, chains and other. It describes sets of values, functions, and rules that these structures must follow. In other words, this specification defines the hierarchy of interfaces for algebraic structures.




A developer would use algebraic structures for a higher level of abstraction and consistent interface. We need to write code asynchronous, with lazy evaluation and error handling — and for each of these cases there is a structure in Fantasy Land. Although, it’s up to you to decide if you’ll use these structures in your everyday work.


My advice for you is to read a great book to get acquainted with algebraic structures in Javascript – Professor Frisby’s Mostly Adequate Guide to Functional Programming – and it just might change your mind.



Lazy Evaluation


Lazy evaluation is natural for functional programming, and to some extent, you will get them simply by using ramda:



This particular example add(1) will be executed only 2 times. Why? Thanks to transducers, composable, and efficient transformation functions.
Transducers allow transformation chair execution while traversing the collection, thus avoiding the creation of intermediate collections:



First, it executes the cycle of 3 iterations for mapping, then the cycle of 3 iterations for filtering. For large collections and more complex transformations, you’ll want to rewrite this code using reduce:



Great, it only takes one cycle. The following code is equivalent:



Let’s implement a filter and map using reducer in order to demonstrate it:



Still 2 cycles. However, since append has reducer interface (acc, x) -> acc, we can compose our reducers and perform mapping and filtering in a single pass:



The transducer solution gives us cleaner syntax, more flexibility in changing transformations chain, and the ability to reuse the code (almost all List functions from ramda can be used as a transducer and run lazy).


And more complicated example in order to demonstrate the work with transduce.js streams:



In this particular case, parse is the transducer, and all magic is hidden in transduce-stream. All that is left to do is implement transformations’ logic. In addition to simple pipeline, we can use parse with other libraries working with transducers (for example RxJS or Highland).



Getting Acquainted with Reactive Programming


Let’s complicate the previous task to demonstrate the idea. Now we need to parse the logs from several files, filter them, and output to stdout. To solve the task, we will use the library Highland that can be found on Github:



The code has not changed much, we have just changed the way we extract the data. It should be easy enough to understand what happens here without access to the documentation of Highland: we read the files, merge them into one stream, transform them with transducer help, and output them to stdout. Highland provides us with the ability to manipulate the streams as collections, so that we can easily use our parse function here.


Reactive programming is a programming with asynchronous data stream — any data, whether it is a server response, database query result, or UI events. This is where the “functional magic” appears. For example, data from several merged streams can be filtered and turned into new stream containing only the necessary data. All this is done with quite familiar merge, map, filter, transduce and so on.





Many elements of functional programming can be included in your everyday work, and you don’t need to retrain or change the stack. If your development team is up for the challenge, give functional programming a shot.


Node.js Software Development Startups Co-Building

Latest Insights in Node.js

The Rise of Kotlin – Moving Away from Java for Android Development

Kotlin is a programming language for the Java Virtual Machine that’s able to be used in any scenarios that currently…

Introducing our Sphere Heroes Program – Artem Korenev – Employee of the month

At Sphere, employee recognition is a key component of our corporate culture. We believe in celebrating the successes of our…

Write For Sphere

Are you a writer with tech expertise? Then we want to hear from you! Here are a few guidelines for…

View All Articles arrow

We are here to help:

checkmarkto become a customer checkmarkto become an investor checkmarkto send a media inquiry checkmarkto join our team checkmarkto simply say ‘hi’
Get in Touch