Monday, December 7, 2020

Closures vs pureness

The other day I was looking at a nested map/reduce/filter constellation which had a bunch of nesting, therefore there were lot of closures. This colleague had an interesting question: "In PHP, usually we can tell the interpreter that a function is relying on something from outside of the function with the `use` keyword, so e.g. we could tell at one level of the nesting that a function not only relying on it's input, but something from the outside (closure). Is there a way to do this in JavaScript?".

Let me show this on an example. (this is a simplified version what you can find at http://reactivex.io/learnrx/ .


Now, are these nested functions pure? No, not really. I couldn't simply unit test them because they need context outside of their closure.

This made me thinking, how could we still achieve pureness?

As anyone, I first tried to Google it (khm DuckDuckGo? Sorry, I'm still not detached from the search giant..). I found this SO thread. The solution seems easy and elegant, how could I not think of that before?

So let's try to refactor our code:

So here you can see that videoBoxartMapper receives 2 arguments, so we can exlicitly depend on the context coming in from the outer function. We could easily achieve that by simply return that function and passing the video argument to it. Tada!

In summary, I think doing these crazy nestings can be harmful from a readability perspective, but as you can see, even this can be refactored in a pure fashion, so yay, we can easily test them, but one needs to have this mindset from day 0 when implementing deeply nested closures.

No comments:

Post a Comment