Never work twice
Some functions are slow but always give the same answer for the same input. Memoizing keeps a note of every answer, so the second time you ask, it answers instantly. You'll build it with closures and higher-order functions.
The idea
function slowSquare(n) {
for (let i = 0; i < 1e7; i++) {}
return n * n;
}
const cache = new Map();
function fastSquare(n) {
if (cache.has(n)) return cache.get(n);
const result = slowSquare(n);
cache.set(n, result);
return result;
}
let t = Date.now();
fastSquare(9);
console.log("first:", Date.now() - t, "ms");
t = Date.now();
fastSquare(9);
console.log("second:", Date.now() - t, "ms");