Explorer
Node.js

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; }; } ```

Memoize Function

Medium
Write a `memoize(fn)` that caches results based on arguments. If the same args are passed again, return the cached result.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"result":3,"calls":2}