×

javascript · level 3 · unit 7 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Memoising trades a little memory for a lot of speed.

Some functions are slow but always give the same answer for the same input, like a big calculation or a server request. them: keep a of answers, and check it before doing any work.

A Map makes a tidy cache: cache.has(key), cache.get(key) and cache.set(key, value). Wrap it in a higher-order memoise function, a closure holding the Map, and you can upgrade any function. Only memoise pure functions: if the answer can change, the cache goes stale.

function memoise(task) {
  const cache = new Map();
  return (key) => {
    if (!cache.has(key)) { cache.set(key, task(key)); }
    return cache.get(key);
  };
}
let calculations = 0;
function slowSquare(n) { calculations++; return n * n; }
const fastSquare = memoise(slowSquare);
console.log(fastSquare(9), fastSquare(9), fastSquare(4), fastSquare(9));
console.log(`Worked out ${calculations} times`);

Caching works for requests to the practice server too: store the promise, and two callers share one request.