Write a `memoize(fn)` that caches results based on arguments. If the same args are passed again, return the cached result.
Problem Statement
Write a `memoize(fn)` that caches results based on arguments. If the same args are passed again, return the cached result.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Use a Map or object to store previous results.
š” Hint 2:
Create a cache key from the arguments (e.g., JSON.stringify(args)).
š” Hint 3:
Check if cache has the key; if yes return cached, else compute, store, and return.
ā
Solution:
```javascript
function memoize(fn) {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const result = fn(...args);
cache.set(key, result);
return result;
};
}
```