Created
May 1, 2010 09:59
-
-
Save jmtame/386206 to your computer and use it in GitHub Desktop.
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
// 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