Overview
Implement memoize(fn) that returns a function caching results based on the first argument.
Constraints
- Cache key is first argument (use it directly)
- Return cached result if same key is called again
Examples
const double = memoize(x => x * 2); double(5); // 10 (computed) double(5); // 10 (cached)
Solution
Reveal solution
function memoize(fn) {
const cache = new Map();
return function(arg) {
if (cache.has(arg)) return cache.get(arg);
const result = fn(arg);
cache.set(arg, result);
return result;
};
}memoize.js
Memoize
mediumcodingJavaScriptFunctions
Overview
Implement memoize(fn) that returns a function caching results based on the first argument.
Constraints
- Cache key is first argument (use it directly)
- Return cached result if same key is called again
Examples
const double = memoize(x => x * 2); double(5); // 10 (computed) double(5); // 10 (cached)
Solution
Reveal solution
function memoize(fn) {
const cache = new Map();
return function(arg) {
if (cache.has(arg)) return cache.get(arg);
const result = fn(arg);
cache.set(arg, result);
return result;
};
}NameTopicDifficulty
103 of 103 problems