Skip to content

Instantly share code, notes, and snippets.

@cburgdorf
Created March 4, 2011 17:39
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 cburgdorf/855338 to your computer and use it in GitHub Desktop.
Save cburgdorf/855338 to your computer and use it in GitHub Desktop.
Function.prototype.cache = function () {
if (this.cache === undefined){
this.cache = {};
}
if (this.cache[arguments[0]] !== undefined){
console.log("using the cache");
return this.cache[arguments[0]]; //I wonder why this works even for object arguments (e.g. {test: 3})? Implicity converted to string?
}
else{
console.log("running method");
return this.cache[arguments[0]] = this.call(this, arguments[0]);
}
};
function isPrime( num ) {
// everything but 1 can be prime
var prime = num != 1;
for ( var i = 2; i < num; i++ ) {
if ( num % i == 0 ) {
prime = false;
break;
}
}
return prime;
}
console.log(isPrime.cache(524287));
console.log(isPrime.cache(524287));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment