Spot the bug - #8

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.

Ellen

You’re creating a Map but reading/writing with cache[id], which just sticks a random property on the Map object instead of using its key store.

Use cache.has/get/set (or switch cache to {} if you really want bracket access).

if (cache[id]) is a bad cache check because a stored 0 or false reads like a miss and you recompute.

Since you’re using a Map, do cache.has(id) and cache.get(id) so falsy values still count as hits.

One more edge case: cache[id] coerces keys to strings, so cache[1] and cache["1"] end up as the same entry, which rather defeats the point of using Map.

if (cache[id]) trips me up the most, since 0 or "" gets treated like a miss and you end up rebuilding. A Map fixes that with cache.has(id), so falsy values still count as cached and you can get them right after.

One more weirdness: by doing cache[id] = user you can accidentally stomp on real Map properties (try id = "size" and now cache. size is an object), which is a fun way to create a “works until it doesn’t” bug.