Complexity Analysis
Time Complexity:
Space Complexity:
Problem Description
Given a function fn, return a memoized version of that function.
A memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value.
Solution
/**
* @param {Function} fn
* @return {Function}
*/
function memoize(fn) {
const cache = new Map();
return function(...args) {
// Create a unique key for the arguments
// Note: For simple primitives, joining is often enough,
// but JSON.stringify handles arrays/objects better as keys
// (though slower and has edge cases with circular refs).
// For this specific problem context where args are JSON serializable:
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn(...args);
cache.set(key, result);
return result;
}
}