maurogestoso
6/18/2017 - 2:16 PM

medium-memoize-3.js

function memoize (func) {
  // define the memoized version of func
  const memoizedFunc = function (input) {
    let result;
    if (memoizedFunc.cache[input] !== undefined) {
      result = memoizedFunc.cache[input];
    } else {
      result = func(input);
      memoizedFunc.cache[input] = result;
    }
    return result;
  }
  
  // give it a cache property
  memoizedFunc.cache = {};

  // return it
  return memoizedFunc;
}

// create our memoized function by passing our original function to memoize
const memoizedSquare = memoize(square);

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

function square (n) {
  console.log('Calling square with', n);
  return n * n;
}