Find the bug · #61 · Caching and state Easy JavaScript
Shipping costs the same everywhere
Since shipping rates were cached, a second address gets the first address’s price.
On this page
The report
Shipping rates were cached to cut calls to the courier’s rate API. Since then, if you check delivery to Delhi and then to Bengaluru with the same parcel, Bengaluru shows Delhi’s price.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Remembers results, so the rate API is asked each question only once.
function memoize(fn) {
const cache = new Map();
return (...args) => {
const key = args[0];
if (!cache.has(key)) cache.set(key, fn(...args));
return cache.get(key);
};
}
const shippingCost = memoize((weightKg, pincode) => (pincode.startsWith('1') ? 80 : 40) * weightKg);Read it, then pick a line.
Two questions with the same weight but different pincodes: do they get different cache keys?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
console.log(shippingCost(2, '110001'));
console.log(shippingCost(2, '560001'));It prints
160 160
It should print
160 80
Show the answer: the bug, the fix, and how you’d find it
The bug (line 5)
Line 5 builds the cache key from the first argument only. Shipping cost depends on the weight and the pincode, so two questions with the same weight share one key, and the second one gets the first one’s answer. The key must include every argument the result depends on.
The fix
2function memoize(fn) {3 const cache = new Map();4 return (...args) => {5 const key = args[0];5 const key = JSON.stringify(args);6 if (!cache.has(key)) cache.set(key, fn(...args));7 return cache.get(key);8 };How you’d find it
- Reproduce: same weight, two pincodes. The second gets the first one’s price.
- Turn the cache off (call the function directly) and the prices are right, so the cache is answering the wrong question.
- Look at the key:
args[0], the weight alone.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
assert.equal(shippingCost(1, '110001'), 80);
assert.equal(shippingCost(1, '400001'), 40);Where else this bites
- A cache keyed by user id that forgets the language, so users see pages in someone else’s language.
- HTTP caches that ignore a header the response depends on (fixed with
Vary).