Skip to content

Instantly share code, notes, and snippets.

@bonza-labs
Created September 15, 2011 23:34
Show Gist options
  • Save bonza-labs/1220799 to your computer and use it in GitHub Desktop.
Save bonza-labs/1220799 to your computer and use it in GitHub Desktop.
Javascript cache wrapping
var $w = function(string) { return string.split(' '); };
var asInts = function(arr) {
var results=[];
for(var i=0, m=arr.length; i<m; i++) results.push(parseInt(arr[i], 10));
return results;
};
Array.prototype.map = function(func) {
var results=[];
for(i=0, m=this.length; i<m; i++) results.push(func(this[i]));
return results;
};
var time = function(subject, label) {
this.seq = 1;
var name = label || this.seq++;
console.time(name);
subject();
console.timeEnd(name);
}
var primes = asInts($w('524287 9369319 2147483647'));
var notprimes = asInts($w('4 6 8 15 21 524284 9369312'));
function isPrime(num) {
if (!num) return false;
var prime = num != 1;
for ( var i = 2; i < num; i++ ) {
if ( num % i == 0 ) {
prime = false;
break;
}
}
return prime;
}
Function.prototype.cached = function() {
var self = this;
if (!self.cache) self.cache = {};
return function(o) {
if (self.cache[o] == null) {
console.log('cache miss');
self.cache[o] = self(o);
} else { console.log('cache hit'); }
return self.cache[o];
}
};
isPrimeCached = isPrime.cached();
time(function(){ primes.map(isPrime); }, 'isprime-no-cache');
time(function(){ primes.map(isPrimeCached); }, 'isprime-with-cache first');
time(function(){ primes.map(isPrimeCached); }, 'isprime-with-cache repeated');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment