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, memoizedFn calls the original callback with those arguments, stores the result in the cache, and then returns the result.
  • The cache should be a Map object 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.

More JS Coding

View all JS Coding →
JS CodingMedium

5. Throttle

JS CodingMedium

13. Deep Clone

JS CodingMedium

14. Event Emitter

JS CodingEasy

66. Promise Methods

JS CodingMedium

86. API Retry

JS CodingEasy

mul(a)(b)(c)

Related hubs

  • All JavaScript coding
  • JavaScript interview questions
  • JS polyfill interview questions
  • Debounce & throttle questions
  • React interview hub
  • Facebook interview

FAQ

What does Memoize test in a frontend interview?

Caching by arguments, closure-based storage, reference vs value keying, and knowing when memoization helps vs hides bugs.

What should a good answer discuss?

Cache key strategy, memory growth, and clearing/invalidating entries when inputs are objects or async work is involved.

Related practice?

Throttle, debounce, and deep clone.