Pure Memoization in JavaScript | Closures Example

function square(num) {
  return num * num;
}

function memoizedSquare() {
  let cache = {}
  return function optimizedSquare(num) {
    //console.log(JSON.stringify(cache));
    if(num in cache) {
      console.log('returning from cache);
      return cache[num];
    }else {
      console.log('computing square');
      const result = square(num);
      cache[num] = result;
      return result;
    }
  }
}

const memoSquare = memoizedSquare();
console.log(memoSquare(10));
console.log(memoSquare(20));
console.log(memoSquare(30));
console.log(memoSquare(30));

No comments:

Post a Comment