JS&TS
May 13, 2024

How to memoize a function in JS?

Here you'll see how to implement the memoize function.

JavaScript

Prelude:

From time to time you perhaps will need create a function which has to memoize your previous function's call.

function memoize(fn) {
  const cache = Object.create(null);
  
  return function(...args) {
    const key = JSON.stringify(args);
    
    for (key in cache) {
      return cache[key];
    }
    
    const result = fn.apply(this, args);
    cache[key] = result;
    
    return result;
  }
}

Steps:

  1. First of all you need create a list;
  2. Second we get the key;
  3. Third check whether key includes in the cache or not;
    1. If it's return cached function;
    2. it it's not invoke the function and cache the result.
  4. Fourth return the result.

Conclusion

Usually the most useful function is't so hard as you may thought.