Spot the bug - #18

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.

Sarah

cache is a Map, but the code is treating it like an object with cache[id], so the “cache hit” path never really uses the Map API.

Fix by either switching to cache.has(id) / cache.get(id) / cache.set(id, user), or change cache to {} if you actually wanted property access.

Yep

Changing cache to {} can bite you hard if id is ever an object — all those keys stringify to "[object Object]" and you silently overwrite entries.

const cache = {};
const id1 = { a: 1 };
const id2 = { a: 2 };

cache[id1] = "user1";
cache[id2] = "user2";

console.log(Object.keys(cache)); // ["[object Object]"]
console.log(cache[id1]); // "user2" (oops)

Map is the boring fix here because it keeps object keys as actual keys, so has/get/set behave the way your brain expects.

const cache = new Map();
cache.set(id1, "user1");
cache.set(id2, "user2");

console.log(cache.has(id1)); // true
console.log(cache.get(id1)); // "user1"

Square brackets on a Map are a trap: cache[id] doesn’t touch the map storage at all, it just slaps a normal property onto the Map object. So it looks fine in a quick test, then cache.clear() does nothing to your “cached” values because they were never in the map in the first place.

Square brackets on a Map don’t “sort of work” — they’re just wrong. cache[id] is a plain object property, so cache.clear() won’t touch it and you get this half-broken cache that lies to you in tests.

The if (cache.get(id)) thing is a separate landmine though. If you can ever cache falsy values, you’ll recompute forever. Use has() for presence and get() for the value, like you showed.

That is clean