AI solution for JavaScript Coding Question on BFE.dev
14. Implement a general memoization function - `memo()`
Here's one possible solution:
function memo(func, resolver = (...args) => args.join('_')) { const cache = {}; return function memoized(...args) { const key = resolver(...args); if (key in cache) { return cache[key]; } const result = func.apply(this, args); cache[key] = result; return result; };}
The memo
function takes in two parameters:
func
, which is the original function that we want to memoize.resolver
, which is an optional function that takes in the arguments tofunc
as input, and returns a key to use for caching.
The memo
function returns a new function that can be used in place of func
. Within this new function, we first generate a cache key based on the arguments passed in, using the resolver
function. We then check if the key is already in the cache - if so, we return the cached value, otherwise, we call the original func
with the given arguments and cache the result.
Note that we're using the spread operator (...
) to pass the arguments to the resolver function and to the original function call. We're also using Function.prototype.apply
to call the original function with the spread-out arguments.
If no resolver
function is provided, we default to using Array.from(arguments).join('_')
as the key generator.
One thing to keep in mind is that this implementation uses an object (cache
) to store the memoized results, so if we call memo()
many times with different functions, or with different argument patterns for the same function, we could end up using a lot of memory. A more sophisticated implementation could use a map or a WeakMap to limit memory usage.