Created
September 15, 2011 23:34
-
-
Save bonza-labs/1220799 to your computer and use it in GitHub Desktop.
Javascript cache wrapping
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
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