Topic Description

When writing code, we often use caching to avoid repeating complex computations. Caching means storing the output of past computations so that if the same input appears again, we can directly use the stored result instead of recomputing it. This effectively saves time. Because caching is so useful, it is frequently used in real-world applications, making functions like memoize a common topic in interviews.

Specifically, memoize accepts a function and returns a new function with caching capabilities. For the returned function, if an input has already been computed, it won't recompute; it will directly return the cached result.

For example, consider a sum function that returns the sum of two parameters:

const sumFn = (a, b) => a + b;

If we apply memoize to the sum function to get a memoizedSum function, it will work as follows:

const memoizedSum = memoize(sumFn);
memoizedSum(2, 2) // 4 - This is computed.
memoizedSum(2, 2) // 4 - This is retrieved from the cache, no computation needed.

Answer

function memoize(fn) {
  const cache = {}
  
  return function(...args){
	  const key = JSON.stringify(args)
	  
	  if(cache.hasOwnProperty(key)){
		  console.log('from cache')
		  return cache[key]
	  }else{
		  const val = fn(...args);
      cache[key] = val;
      return val;
	  }
	  
  }
}