$ ./guess_the_languageProblem Solving — fix the bug
Problem Solving — fix the bug · hard · #108

Which fix removes the subtle bug?

const cache = {};
function get(key) {
  if (cache[key]) return cache[key];
  cache[key] = compute(key);
  return cache[key];
}
  1. Test presence with key in cache instead
  2. Test presence with cache[key] != null
  3. Initialise the cache as new Set() first
  4. Return cache[key] || compute(key) only
A cached 0, '' or false is falsy, so the value is recomputed every call.
Play Problem Solving ▸