Skip to content

Instantly share code, notes, and snippets.

@bradpauly
Created March 8, 2013 16:22
Show Gist options
  • Save bradpauly/5117659 to your computer and use it in GitHub Desktop.
Save bradpauly/5117659 to your computer and use it in GitHub Desktop.
Function.prototype.cache = function(){
var _cache = {};
this.store = function(n, v){
_cache[n] = v;
return v;
}
this.fetch = function(n) {
if (n in _cache) {
return _cache[n];
} else {
return null;
}
}
return this;
}();
function isPrime(num) {
if (isPrime.cache.fetch(num) != null) {
return isPrime.cache.fetch(num);
}
var prime = num != 1;
for ( var i = 2; i < num; i++ ) {
if ( num % i == 0 ) {
prime = false;
break;
}
}
return isPrime.cache.store(num, prime)
}
function sin(num) {
if (sin.cache.fetch(num) != null) {
return sin.cache.fetch(num);
}
var s = Math.sin(num)
return sin.cache.store(num, s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment