Skip to content

Instantly share code, notes, and snippets.

@RANUX
Created March 29, 2018 14:53
Show Gist options
  • Save RANUX/28605ef1b86b442cfc657c0d2ecc4d99 to your computer and use it in GitHub Desktop.
Save RANUX/28605ef1b86b442cfc657c0d2ecc4d99 to your computer and use it in GitHub Desktop.
Computed (cached) function value JS pattern
function isPrime(value) {
// create cache
if (!isPrime.answers) {
isPrime.answers = {};
}
// check was value cached
if (isPrime.answers[value] !== undefined) {
return isPrime.answers[value];
}
var prime = value !== 0 && value !== 1; // 1 - non prime
for (var i = 2; i < value; i++) {
if (value % i === 0) {
prime = false;
break;
}
}
return isPrime.answers[value] = prime;
}
console.log(isPrime(5));
console.log(isPrime(5));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment