Skip to content

Instantly share code, notes, and snippets.

@madrobby
Created December 14, 2009 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madrobby/255941 to your computer and use it in GitHub Desktop.
Save madrobby/255941 to your computer and use it in GitHub Desktop.
// Cache results for functions with one argument
Function.prototype.cached = function(){
var self = this, cache = {};
return function(arg){
if(cache[arg]) return cache[arg];
return cache[arg] = self(arg);
}
}
// Same, but with some tracing:
Function.prototype.cached = function(){
var self = this, cache = {};
return function(arg){
if(cache[arg]) {
console.log('Cache hit for '+arg);
return cache[arg];
} else {
console.log('Cache miss for '+arg);
return cache[arg] = self(arg);
}
}
}
// Let's give it a shot
function isPrime(num) {
var prime = num != 1;
for ( var i = 2; i < num; i++ ) {
if ( num % i == 0 ) {
prime = false;
break;
}
}
return prime;
}
isPrime = isPrime.cached();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment