Memoize a function in JavaScript

Create a function in JavaScript that memoizes or caches the result for the given input so that the subsequent calls for the same inputs will be faster.

Example

slowFunc(params) // normal call, slow output

const memoized = memoize(slowFunc);
memoized(params) //first call, extremely slow -> caches the result
memoized(params) //second call, very fast.
//all the subsequents call for the same input will be faster.

memoized(differentParams) //first call, extremely slow -> caches the result
memoized(differentParams) //second call, very fast.

Memoization is an optimization technique prominently used in computer science to avoid recomputation in intensive computation, we cache the result for the given input and return it for subsequent call of the same input rather than performing the expensive computation again.

From the definition, I assume you may have got a good understanding of what we are trying to implement.

We will create a closure with the higher-order function that will cache the result for the given input. If a call is made and the result for the input is stored in the cache then we will return it, otherwise, execute the function and cache its result.

const memoize = function(fn){
  const cache = {};
  return function(){
    //arg as key to store the result
    const KEY = JSON.stringify(arguments);
    
    //if the result is present for the given key return it
    if (cache[KEY]) {
      return cache[KEY]
    }
    
    //else compute and store the result and return the result
    const evaluatedValue = fn(...arguments);
    cache[KEY] = evaluatedValue;
    return evaluatedValue;
  }
};
Input:
function factorial(n) {
   if(n === 0 || n === 1) {
     return 1
   }
   return factorial(n-1) * n; 
}

const memoizedFactorial = memoize(factorial)
let a = memoizedFactorial(100) // slow
console.log(a);
let b = memoizedFactorial(100) // faster
console.log(b);

Output:
9.33262154439441e+157 // slow
9.33262154439441e+157 // faster