DEV Community

chandra penugonda
chandra penugonda

Posted on • Edited 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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay