|
| 1 | +```js |
| 2 | +/** |
| 3 | + * Creates a memoized version of the given function. |
| 4 | + * |
| 5 | + * @param {Function} func - The function to memoize. |
| 6 | + * @returns {Function} - A memoized version of the function. |
| 7 | + */ |
| 8 | +export default function memoize(func) { |
| 9 | + if (typeof func !== 'function') { |
| 10 | + throw new TypeError('Expected a function'); |
| 11 | + } |
| 12 | + |
| 13 | + const cache = new Map(); // Create a cache to store results based on arguments |
| 14 | + |
| 15 | + return function (arg) { |
| 16 | + // Check if the result for this argument is already cached |
| 17 | + if (cache.has(arg)) { |
| 18 | + return cache.get(arg); // Return the cached result |
| 19 | + } |
| 20 | + |
| 21 | + const result = func(arg); // Compute the result if not cached |
| 22 | + cache.set(arg, result); // Store the result in the cache |
| 23 | + return result; // Return the calculated result |
| 24 | + }; |
| 25 | +} |
| 26 | +``` |
| 27 | +### Explanation |
| 28 | +#### Validate Input: |
| 29 | + |
| 30 | +* Ensure that func is a valid function; throw a TypeError if not. This prevents accidental usage with invalid inputs. |
| 31 | +#### Create a Cache: |
| 32 | + |
| 33 | +* Use a `Map object` to store computed results for each unique input argument. Map is preferred over plain objects because it supports any type of key and offers better performance for storing and retrieving data. |
| 34 | +#### Return a Memoized Function: |
| 35 | + |
| 36 | +* The memoized function is a `closure` that has access to the cache object. It checks if the result for the given argument is already present in the cache. |
| 37 | +#### Check Cache: |
| 38 | + |
| 39 | +* If the `arg` is already in the `cache`, return the cached result. |
| 40 | +#### Compute and Store Result: |
| 41 | + |
| 42 | +* If the `arg` does not exist in the `cache`, compute the result by calling the original `func(arg)`. |
| 43 | +* Store the result in the `cache` for future lookups. |
| 44 | +* Return the newly computed result. |
0 commit comments