Refactoring Javascript: Collection Pipelines

Michael Timbs
The Startup
Published in
4 min readAug 29, 2020

--

Refactoring Javascript: Collection Pipelines

This is the first post in a series of posts about refactoring your Javascript code to use map, filter and reduce instead of loops. I refer to this style of programming as Collection Pipelines as I was first introduced to this concept in Martin Fowler’s Refactoring.

One of the first control structures we learn as programmers is loops. In Javascript, loops still tend to be the default way for people to process collections, despite the language having excellent support for higher order functions (fancy name for functions that take a function as an input and returns another function) such as map(), filter() and reduce().

I’ve worked on some truly gnarly code over the years — some of it was even written by other people. A recurring theme I have noticed is that a lot of complexity arises from using loops to iterate over a collection of objects. What begins as an innocent looking loop, somehow mutates into some beast of complexity with nested conditionals, variable references 20 lines up the page, and pyramid style code of nested logic. Perhaps the most nefarious risk in using loops is what I refer to as Responsibility Creep. A piece of code starts with a single, narrow responsibility and over time developers add “just a little bit more” logic to handle some new edge case or data flow path. A year later and your innocent loop has turned into a true…

--

--

Michael Timbs
The Startup

Full-stack developer. In love with Typescript and Serverless