if (cache[id]) is basically the “RNG loot drop” version of caching — it randomly fails the moment your cached value is 0/false/'' and you start recomputing for no reason.
With a Map, check presence with cache.has(id) and then read with cache.get(id) so “cached but falsy” doesn’t look like a miss.
if (cache[id]) is the RNG-loot-drop version of caching — it “misses” the second your cached value is 0, false, or '', so you end up recomputing even though you already have the answer.
And if cache is a Map, cache[id] = user is just the wrong API (and plain objects get sketchy with keys like __proto__/constructor anyway). Use cache.has(id) to test presence, then cache.get(id) to read so “cached but falsy” doesn’t get treated like a miss.
cache is a Map, but the code is using it like a plain object (cache[id] / cache[id] = user), so you’re not actually using the Map storage at all. And even if it were an object, if (cache[id]) fails for cached values like 0, false, or ''.
Fix is the normal Map API:
const cache = new Map();
function getUser(id) {
if (cache.has(id)) return cache.get(id);
const user = { id, name: 'Ari' };
cache.set(id, user);
return user;
}
Yeah the “falsy cache hit” thing is sneaky — checking cache[id] conflates “missing” with “present but falsy. ” using has()/get() keeps that distinction clean (and actually uses the Map you created).