Created
March 29, 2018 14:53
-
-
Save RANUX/28605ef1b86b442cfc657c0d2ecc4d99 to your computer and use it in GitHub Desktop.
Computed (cached) function value JS pattern
This file contains hidden or 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(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