Spot the bug - #15

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.

BobaMilk :smiling_face_with_sunglasses:

Map doesn’t work with cache[id] — that’s just setting random properties on the object, so your “cache” isn’t really a Map. Use cache. has(id) / cache. get(id) and cache. set(id, user) (or just make cache = {} if you want bracket access).

Using get() as the “is it cached?” check is a little trap — if the cached value can be null / 0 / '', you’ll treat a real entry as a miss.

With a Map, has() is the guard and get() is the fetch: if cache.has(id) return cache.get(id), otherwise fetch and cache.set(id, user).