Extracting a Pure Function
A real-life example of making logic reusable by refactoring to use a pure function.
Recently I’ve been working with mapping APIs. When moving from one map provider to another, there was some tricky logic that I wanted to reuse, but first I needed to detangle it.
I’m not going to explain how the function works, mostly because I’m lazy and that would be difficult, but also because it’s not particularly relevant.
Suffice to say, we need to do some calculations to determine a min/max zoom level, and then we need to update the map object with those values.
In the original implementation, the logic of determining this is intermixed with the details of updating the map. Not only does this make it harder to understand the logic, it makes it impossible to re-use the logic.
To visualize this, I’ve highlighted the logic and implementation details in the origindifferent colors, below:
In order to make a reusable function, I wanted to move the logic into a pure function, separating it from the implementation details of the specific map:
After which, the original function becomes a call to our new pure function, and a single pair of mutations:
The logic is still tricky — we haven’t changed anything there. The advantages of using a pure function for the logic are:
1. The pure function is “done” — there’s no reason for it to ever change (unless of course there’s a bug in our logic). Factor your system so that artifacts that change at similar rates are together.
2. If we need a different calculation in the future, we can delete this function and replace it with a different one. Write code that’s easy to delete.
3. It’s easy to unit test — simply assert that a given input returns the expected output. You could use a table-driven test.



