The challenge
Write memoize(fn) that returns a function taking ONE argument. The first time it sees an argument, it calls fn and remembers the result. Next time, it returns the remembered result without calling fn.
Try it
Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.
It prints
What the tests check
- Repeat arguments are cached:
(() => { let calls = 0; const sq = memoize((n) => { calls++; return n * n; }); sq(4); sq(4); sq(5); return [sq(4), calls]; })()gives[16, 2] - Different types are different keys:
(() => { const id = memoize((x) => x); return [id(0), id("0")]; })()gives[0, "0"]
Hints
Stuck? Open one hint at a time. Try again after each one.
Hint 1
A Map is perfect for the cache: its keys can be any type.
Hint 2
if (cache.has(arg)) return cache.get(arg);
A solution
There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.
Show one possible solution
function memoize(fn) {
const cache = new Map();
return (arg) => {
if (!cache.has(arg)) cache.set(arg, fn(arg));
return cache.get(arg);
};
}
Learn what you need
This exercise uses what Grade 13: Modern JavaScript Power-Ups teaches. Read those notes first if any of it is new.