Memoization with cache and closure

In order to understand how dynamic programming works we need to understand what caching means “caching” is a way to store values so you can use them later on.

function multiplyTwo(n) {
  console.log("take calculation time");
  return n * 2;
}

console.log(multiplyTwo(5));
console.log(multiplyTwo(5));
console.log(multiplyTwo(5));
take calculation time
10
take calculation time
10
take calculation time
10
  • We call the same function 3 times.

Cache or Memoization

let cache = {
  1: 2,
  2: 4,
  3: 6,
};

function cachedMultiplyTwo(n) {
  if (n in cache) {
    return cache[n];
  } else {
    console.log("take calculation time");
    cache[n] = n * 2;
    return cache[n];
  }
}

console.log(cachedMultiplyTwo(5));
console.log(cache);
console.log(cachedMultiplyTwo(5));
console.log(cachedMultiplyTwo(5));
take calculation time
10
{ '1': 2, '2': 4, '3': 6, '5': 10 }
10
10
  • Object (Hash Table) Big O is O(1) which is fast.

What is memorization?

memorization is a specific form of caching that involves caching the return value of a function that is the return value of a function that is the return value of the function based on its parameters, and if the parameter of the function does not change it is memorized it uses the cache because it is calculated the same thing before with the same parameter.

With memorization, the function does not have to calculate it again.

Ideally, you do not want to file the cache in Global Scope. That is to be living outside the function. Ideally, it is good practice to have memory or the cache to live inside of the function. There are many ways to do this based on the language. However, in JavaScript that we can use something called closures.

Closures with Memorization

function closureCaheMultiplyTwo() {
  let cache = {};
  return function (n) {
    if (n in cache) {
      return cache[n];
    } else {
      console.log("take calculation time");
      cache[n] = n * 2;
      return cache[n];
    }
  };
}

const cacheForMultiplyTwo = closureCaheMultiplyTwo();
console.log(cacheForMultiplyTwo(2));
console.log(cacheForMultiplyTwo(2));
console.log(cacheForMultiplyTwo(2));
console.log(cacheForMultiplyTwo(3));
take calculation time
4
4
4
take calculation time
6

Leave a Reply

Your email address will not be published.

ANOTE.DEV