Skip to content

Instantly share code, notes, and snippets.

@jmtame
Created May 1, 2010 09:59
Show Gist options
  • Save jmtame/386206 to your computer and use it in GitHub Desktop.
Save jmtame/386206 to your computer and use it in GitHub Desktop.
// http://ejohn.org/apps/learn/#20
// caching results from a js function
function isPrime( num ) {
var prime = num != 1; // Everything but 1 can be prime
if (isPrime.cache[num]) {
result = isPrime.cache[num];
} else {
for ( var i = 2; i < num; i++ ) {
if ( num % i == 0 ) {
prime = false;
break;
}
}
isPrime.cache[num] = prime;
return prime;
}
}
isPrime.cache = {};
assert( isPrime(5), "Make sure the function works, 5 is prime." );
assert( isPrime.cache[5], "Is the answer cached?" );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment