The task is to implement a general memoization function.
The boilerplate code:
function memo(func, resolver) {
// your code here
}
Create a cache storage
const cache = new Map();
Map allows any type of key, and is faster and safer than a plain object. A wrapped function is returned
return function(...args) {}
To generate a cache key, the user determines how arguments map to a cache key.
return function (...args) {
const key = resolver
? resolver(...args)
: args.length === 1
? args[0]
: JSON.stringify(args);
}
Check if the cache exists. If it does, return the result immediately
if (cache.has(key)) {
return cache.get(key);
}
Call the original function once, and save the result for future calls
const result = func.apply(this, args);
cache.set(key, result);
The final code
function memo(func, resolver) {
// your code here
const cache = new Map();
return function(...args) {
const key = resolver ? resolver(...args) : args.length === 1 ? args[0] : JSON.stringify(args);
if(cache.has(key)) {
return cache.get(key);
}
const result = func.apply(this, args);
cache.set(key, result);
return result;
}
}
That's all folks!
Top comments (0)