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.
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.
cache is a Map, but the code is treating it like a plain object (cache[id]), so you’re not actually using the Map storage at all. The fix is to use the 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;
}
Why it matters: cache[id] just sets a normal property on the Map object, which can behave weirdly and won’t participate in Map semantics (like key types, size, and iteration). I found a related kirupa. com article that can help you go deeper into this topic.
:: Copyright KIRUPA 2024 //--