Skip to content

Instantly share code, notes, and snippets.

@arian
Created December 26, 2010 15:48
Show Gist options
  • Save arian/755485 to your computer and use it in GitHub Desktop.
Save arian/755485 to your computer and use it in GitHub Desktop.
Function.prototype.memoize
// A memoize function to store function results of heavy functions
Function.prototype.memoize = function(hashFn, bind){
var memo = {},
self = this;
if (!hashFn) hashFn = function(arg){
return arg;
};
return function(){
var key = hashFn.apply(self, arguments);
return (key in memo) ? memo[key] : (memo[key] = self.apply(bind, arguments));
};
};
var isPrime = function(num){
var i = num - 2;
while (i--) if (num % (i + 2) == 0) return false;
console.log('Prime calculated of ' + num);
return true;
}
var isPrimeFast = isPrime.memoize();
// Calculate the first primes twice
// since they will not change over time, we can use the memoized function
for (var i = 0; i < 1000; i++) if (isPrimeFast(i)) console.log('prime found: ' + i);
for (var i = 0; i < 1000; i++) if (isPrimeFast(i)) console.log('prime found again: ' + i);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment