Skip to content

Instantly share code, notes, and snippets.

@Williammer
Created June 10, 2014 05:10
Show Gist options
  • Select an option

  • Save Williammer/fdf687ee68a46ed10a39 to your computer and use it in GitHub Desktop.

Select an option

Save Williammer/fdf687ee68a46ed10a39 to your computer and use it in GitHub Desktop.
javaScript.fnObjCacheFn.js - the function cache itself with its own property.
function isPrime(value) {
if (!isPrime.anwers) isPrime.answers = {};
if (isPrime.answers[value] != null) {
return isPrime.answers[value];
}
var prime = value != 1; // 1 can never be prime
for (var i = 2; i < value; i++) {
if (value % i == 0) {
prime = false;
break;
}
}
return isPrime.answers[value] = prime;
}
assert(isPrime(5), "5 is prime!");
assert(isPrime.answers[5], "The answer was cached!");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment