DEV Community

chandra penugonda
chandra penugonda

Posted on • Updated on

Javascript Memoized Functions

Memoization is an optimization technique that makes applications more efficient and hence faster. It does this by storing computation results in cache, and retrieving that same information from the cache the next time it's needed instead of computing it again.

function memoize(fn) {
  const cache = new Map();
  return (...args) => {
    const key = JSON.stringify(args);
    if (cache.has(key)) {
      console.log(`fetching from cahce for args ${key}`);
      return cache.get(key);
    }
    const data = fn.apply(this, args);
    cache.set(key, data);
    return data;
  };
}

Enter fullscreen mode Exit fullscreen mode
const addThreeNums = (a, b, c) => a + b + c;
const add = memoize(addThreeNums);
console.log(add(1, 2, 3));
console.log(add(1, 2, 3));

const factorial = memoize((x) => {
  if (x === 0) return 1;
  else return x * factorial(x - 1);
});

console.log(factorial(5));
console.log(factorial(6));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)