javascript · level 3 · unit 7 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Two calls for the same user at once. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
let requests = 0;
const cache = new Map();
function getUser(id) {
if (!cache.has(id)) {
requests++;
cache.set(id, fetch(`https://api.example.com/users/${id}`).then((r) => r.json()));
}
return cache.get(id);
}
const [a, b] = await Promise.all([getUser(1), getUser(1)]);
const c = await getUser(2);
console.log(a.name, b.name, c.name, `requests: ${requests}`);
your turn
Your turn. Memoise a VAT calculator.
Fill in the Map method that asks whether a key is already stored, then pick a price in pence for the first call. Try 500 and watch the count drop.
fix it
Two adults pay the same as one. Can you fix it?
- Two different questions got the same answer. What is the cache key made from?
- The key uses only
a, sofare(3, 1)andfare(3, 2)share one slot in the cache. - Build the key from both inputs:
const key = a + "," + b;, then press run.
nailed it
your functions remember their answers. :D
- Memoising checks a cache before doing slow work.
- The cache key must include every input.
- Only memoise pure functions, or answers go stale.
new words in your collection
- memoise
- cache
This lesson isn’t saved. A free account remembers every lesson you finish.