Created
December 14, 2009 09:38
-
-
Save madrobby/255941 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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