Which fix removes the subtle bug?
const cache = {};
function get(key) {
if (cache[key]) return cache[key];
cache[key] = compute(key);
return cache[key];
}
- Test presence with
key in cacheinstead - Test presence with
cache[key] != null - Initialise the cache as
new Set()first - Return
cache[key] || compute(key)only
A cached 0, '' or false is falsy, so the value is recomputed every call.
Play Problem Solving ▸