maurogestoso
6/18/2017 - 10:46 AM

medium-memoize-1.js

// define a complex computation
function square (n) {
  console.log('Calling square with', n);
  return n * n;
}

// define a place to store computed results
const cache = {};

function memoizedSquare (n) {
  let result;
  // check if n is in the cache
  if (cache[n] !== undefined) {
    // n is in the cache, put its value in result
    result = cache[n];
  } else {
    // n is not in the cache, compute its value and store it in result
    result = square(n);
    // also store the result in the cache for later
    cache[n] = result;
  }
  return result
}

console.log(memoizedSquare(2));
console.log(cache);
console.log(memoizedSquare(2));