19. Memoize I
Difficulty: easy
Create a function memoize that enhances the efficiency of function calls by caching the results. Given a callback function and an optional resolver function, memoize should return a new function that remembers the results of previous invocations with specific arguments, thereby avoiding redundant calculations for the same inputs.
The returned function, memoizedFn, should operate as follows:
- It checks if the result for a given set of arguments is already stored in a cache. If so, it returns the cached result instead of executing the callback again.
- If the result for the given arguments is not in the cache,
memoizedFncalls the original callback with those arguments, stores the result in the cache, and then returns the result. - The cache should be a
Mapobject where keys represent argument combinations, and values are the callback results for those arguments.
Additionally, memoizedFn includes methods for cache management:
has: Checks if a result for a specific set of arguments is already cached.delete: Removes the cached result for a specific set of arguments.clear: Clears the entire cache.
The optional resolver function, if provided, generates a custom key for caching based on the arguments passed to memoizedFn. If not provided, the key is generated by stringifying the arguments.
This memoization technique is particularly useful for optimizing performance in applications with heavy computational functions or expensive database queries that are frequently called with the same arguments.