Skip to content

Instantly share code, notes, and snippets.

@ibolmo
Forked from arian/Function.prototype.memoize.js
Created December 26, 2010 22:47
Show Gist options
  • Save ibolmo/755698 to your computer and use it in GitHub Desktop.
Save ibolmo/755698 to your computer and use it in GitHub Desktop.
// A memoize function to store function results of heavy functions
(function(slice){
Function.prototype.memoize = function(hashFn, bind){
var cache = {}, self = bind ? this.bind(bind) : this, hashFn = hashFn || JSON.stringify;
return function(){
return ((key = hashFn(slice.call(arguments))) in cache) ? cache[key] : (cache[key] = self(key));
};
};
})(Array.prototype.slice);
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