Overview
Implement memoize(fn) that caches results across any number of arguments. Must distinguish different argument combinations correctly.
Constraints
- Support any number of arguments
- Correctly distinguish
[1, 2]from[1]and[2] - Use a trie-like cache structure or composite keys
Examples
const add = memoize((a, b) => a + b); add(1, 2); // 3 (computed) add(1, 2); // 3 (cached) add(2, 1); // 3 (computed — different args)
Solution
Reveal solution
function memoize(fn) {
const cache = new Map();
return function(...args) {
let node = cache;
for (const arg of args) {
if (!node.has(arg)) node.set(arg, new Map());
node = node.get(arg);
}
if (node.has('__result__')) return node.get('__result__');
const result = fn(...args);
node.set('__result__', result);
return result;
};
}memoize-ii.js
Memoize II
mediumcodingJavaScriptFunctions
Overview
Implement memoize(fn) that caches results across any number of arguments. Must distinguish different argument combinations correctly.
Constraints
- Support any number of arguments
- Correctly distinguish
[1, 2]from[1]and[2] - Use a trie-like cache structure or composite keys
Examples
const add = memoize((a, b) => a + b); add(1, 2); // 3 (computed) add(1, 2); // 3 (cached) add(2, 1); // 3 (computed — different args)
Solution
Reveal solution
function memoize(fn) {
const cache = new Map();
return function(...args) {
let node = cache;
for (const arg of args) {
if (!node.has(arg)) node.set(arg, new Map());
node = node.get(arg);
}
if (node.has('__result__')) return node.get('__result__');
const result = fn(...args);
node.set('__result__', result);
return result;
};
}NameTopicDifficulty
103 of 103 problems