Object oriented programming makes code understandable by encapsulating moving parts. Functional programming makes code understandable by minimizing moving parts. — Michael Feathers
This post walks through a set of examples, demonstrating how certain array/collection related features could be implemented in an imperative style, how this could be simplified with lodash, and then a few tweaks that can be made to do the same with pure ES2015.
We’ll use the basic todo.json file seen below to demonstrate each of the techniques in turn.
Finding an Object – The Old Way
With the old way of doing things we need to iterate over each of the todo items, and check whether the object matches the search criteria we are looking for:
This code is verbose and can be a pain to read.
Finding an Object – Lodash
Finding an Object – ES2015
Simple, terse, and works out of the box.
Filtering Objects – The Old Way
Another bread and butter technique is creating a filtered list of objects that match some specific criteria. Let’s get a list of all of the completed todo items:
Filtering Objects – Lodash
A nicer way to do this is using the _.filter() method from lodash:
Filtering Objects – ES2015
We can now achieve the same thing natively with ES2015:
Projections – The Old Way
Following along with the theme, the old way of creating a projection (a list of objects representing a transformation of an existing set of objects) is to iterate through the original list and push each of the projected items into a new list. In our case we want to a new list of objects containing the id and tag count of each todo item:
Projections – Lodash
Again, lodash makes this simpler with the _.map() function:
Projections – ES2015
Again, we can do away with lodash for this scenario in favour of pure ES2015 by simply re-arranging the code slightly:
Reductions – The Old Way
If I want to produce a list of the tags from all of the todo items as a single string, the old imperative way of doing it would be to firstly loop through all of the todo-items to create a list of all of the tags, then loop through the tag list to create the concatenated string:
This could be simplified, but I’ve kept it as verbose as possible to make demonstrate a point.
Reductions – Lodash
We can use the lodash _.reduce() method to simplify this and remove the mutation:
Reductions – ES2015
We can also do the same thing with ES2015 by removing the lodash related syntax: