JavaScript Memoize Example

by LyndseyB

JavaScript

const memoize = (func) => {
	const cache = {};
  
  return function() {
  	const key = JSON.stringify(arguments);
    
    if (cache[key]) {
    	console.log("retrieving from cache", key);
      return cache[key];
    }
    
    const returnVal = func.apply(this, arguments);
    cache[key] = returnVal;
    
    console.log("doesn't exist, adding to cache....", returnVal);
    
    return returnVal;
  }
};

const adder = memoize((n) => {
	return n + 1;
});

adder(10);
adder(11);
adder(10);
adder(11);