The pitfalls of caching
Mutating objects is something we do on a regular basis in Javascript. Once in awhile this can get you into a heap of trouble as I found out the hard way.
# The problem
The other day I had a piece of code that kept giving the same output even though I was setting the output.id
with different values.
const func = require('third-party-library');
const val1 = 'foo';
const val2 = 'foo';
const results = [val1, val2]
.map((v, index) => {
const output = func(v); // returns { content: 'foo' }
output.id = index;
return output;
});
console.log(
results[0].id === results[1].id)
); // true <--- wtf???
After I browsed the source of the third-party library, I noticed it was caching the output. That meant that the output I was modifying was the same on each iteration.
# The solution
The way I got around this was to do a deep copy of the output before the mutation to guarantee purity. The downside to this was the performance hit. Thankfully, performance wasn't my bottleneck here.
# When possible go for pure functions
Pure functions leave no surprises. Another idea is to provide options to disable caching, leaving the developer to decide whats best for themselves. So, the next time you decide to do some caching, just be extra careful, especially if its returning an object.
Subscribe to the newsletter
No spam. Unsubscribe any time.