Spot the bug - #25

There is one deliberate bug here.

const cache = new Map();

function getUser(id) {
  if (cache[id]) return cache[id];
  const user = { id, name: 'Ari' };
  cache[id] = user;
  return user;
}

Reply with what is broken and how you would fix it.

WaffleFries

Clean

You’ve got a Map but you’re indexing it like an object (cache[id]), which just slaps a property onto the instance instead of using the map storage.

Use the real Map API (cache.has(id), cache.get(id), cache.set(id, value)) and it’ll stop doing spooky stuff, especially once id isn’t a string.

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.

Yep — two things are busted here:

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).