Implement memoize
Write memoize(fn, resolver): return a function that caches fn's result per key.
- The key is
resolver(...args), and by defaultJSON.stringify(args), so all arguments count. - A cached result is reused even when it is
0orundefined. - The wrapper forwards
this, and each memoized function has its own cache.
const add = memoize((a, b) => a + b); add(1, 2); add(1, 2); // fn runs once add(2, 1); // a different key: fn runs again
Hints
Hint 1
memoize closes over a Map. Test membership with cache.has(key), not a truthy lookup, so cached 0 and undefined results count as hits.
Hint 2
Return a function, not an arrow, and call fn.apply(this, args) so a memoized method still sees its object.