Some functions are slow, but always give the same answer for the same arguments. To memoize such a function is to wrap it so it remembers. The first call with some arguments does the real work and keeps the answer in a cache. A later call with the same arguments gets the kept answer, without running the function again.
Here is how code uses it, with another function:
const slowSquare = (n) => {
console.log("computing");
return n * n;
};
const square = memoize(slowSquare);
square(4); // prints computing, returns 16
square(4); // returns 16 from the cache: no computing
square(5); // new arguments: prints computing, returns 25
The cache is a Map, made once inside memoize: every call of the returned function shares it, and each memoized function has its own. Its keys are JSON.stringify(args): the arguments 12, 2 give the text "[12,2]", the same for every call with those values, even when an argument is a new array. Ask the cache with has, not by testing the answer, because an answer can be 0 or undefined.
The check counts the real calls of each function. Part of what it must print:
total(12, 2) returns 24, real calls: 1
total(12, 2) returns 24, real calls: 1
total(7, 3) returns 21, real calls: 2
total(2, 12) returns 24, real calls: 3
stock("Notebook") returns 0, real calls: 1
stock("Notebook") returns 0, real calls: 1
sum([12, 7, 29]) returns 48, real calls: 1
sum([12, 7, 29]) returns 48, real calls: 1
Your task: write memoize(fn) in solution.js. It returns a function that answers like fn, but calls fn only once for each list of arguments.
Assignment
Follow the Coding Tutorial to return a function that calls fn, then add the cache: a Map, a key from JSON.stringify, storing each answer, and looking it up first.
Hint
The cache goes inside memoize but outside the returned function, so it is shared by every call and not by other memoized functions. cache.has(key) is true even when the stored answer is 0.
Free plan: 30 tutor messages. PRO is unlimited.
