Skip to content

Instantly share code, notes, and snippets.

@sranso
Last active August 29, 2015 13:57
Show Gist options
  • Save sranso/9772069 to your computer and use it in GitHub Desktop.
Save sranso/9772069 to your computer and use it in GitHub Desktop.
// MEMOIZE, caching something
// generating ids for all the functions
// "crazy closures" allow for the vars / functions to live
// and behave the way we want them to.
(function() {
var id = 0;
function generateId() { return id++; };
Function.prototype.id = function() {
var newId = generateId();
this.id = function() { return newId; };
return newId;
}
})();
var slowFunction = function(x, y) {
for (var i = 0; i < 10; i++) {
console.log(i);
};
return x * y + 15;
};
var anotherSlowFunction = function(x, y) {
for (var i = 0; i < 5; i++) {
console.log(i);
};
return x + y + 5;
};
var memoize = function(fn) {
// answers is now a "private var"--no one can reference
// var answers except for this return function
// because of scope in js, methods can only access vars
// either inside or one level outside
var answers = {};
return function() {
var keys = Array.prototype.slice.call(arguments);
var fnId = fn.id();
if (! answers[fnId]) {
answers[fnId] = {};
};
if (! answers[fnId][keys]) {
answers[fnId][keys] = fn.apply(this, arguments);
};
return answers[fnId][keys];
};
};
// both of these functions now hold the return function
// from var memoize, above
var memoizedSlowFunction = memoize(slowFunction);
var memoizedAnotherSlowFunction = memoize(anotherSlowFunction);
// now to use the memoized functions. is it actually faster? spoiler..
var beforeFirst = new Date();
memoizedSlowFunction(10, 2);
var afterFirst = new Date();
console.log("time to make first call " + (afterFirst - beforeFirst) );
var beforeSecond = new Date();
memoizedSlowFunction(10, 2);
console.log("time to make second call " + ( (new Date()) - beforeSecond ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment