Last active
December 11, 2015 03:58
-
-
Save alloyking/4541221 to your computer and use it in GitHub Desktop.
cache function result
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
function isPrime( num ) { | |
if ( isPrime.cache[ num ] != null ) | |
return isPrime.cache[ num ]; | |
var prime = num != 1; // Everything but 1 can be prime | |
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], "Make sure the answer is cached." ); | |
////////////// - element cache | |
function getElements( name ) { | |
var results; | |
if ( getElements.cache[name] ) { | |
results = getElements.cache[name]; | |
} else { | |
results = document.getElementsByTagName(name); | |
getElements.cache[name] = results; | |
} | |
return results; | |
} | |
getElements.cache = {}; | |
log( "Elements found: ", getElements("pre").length ); | |
log( "Cache found: ", getElements.cache.pre.length ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment