Simple memoizer function

wanted to see if I could still do this from ... memory.

by Andrew Holloway

HTML

<h1>Open the Console</h1>

JavaScript

var memoize = function(fn, context) {
  var cache = {};
  var pContext = (typeof context !== "undefined") ? context : null;
  
  return function() {
  	var key = Array.prototype.join.call(arguments, "__");
    (typeof cache[key] === "undefined" ) && (cache[key] = fn.apply(pContext, arguments));
    return cache[key];
  }
};

var dirtyFunction = function() {
	// just a little something that will take a long time (change loop var to test)
	let x = 0;
	for(var i = 0; i < 100; i++) x++;
  return x;
};

var pow = memoize(dirtyFunction);

// using raw function
var start = new Date(), end, x, max = 10000000;
for (var i = 0; i < max; i++) {
	x = dirtyFunction();
}
end = new Date();

console.log('raw runtime', end - start, x);

// using memoized version (w/ caching), literally 1000x slower
start = new Date();
for (i = 0; i < max; i++) {
	x = pow();
}
end = new Date();

console.log('memoized runtime', end - start, x);