Skip to content

Instantly share code, notes, and snippets.

@binario200
Created April 8, 2018 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save binario200/90fa073ee96abc8f28a659c56a739a1a to your computer and use it in GitHub Desktop.
Save binario200/90fa073ee96abc8f28a659c56a739a1a to your computer and use it in GitHub Desktop.
Memoizing with is prime function
function isPrime(value) {
   // creates the cache
   if(!isPrime.answeres) {
      isPrime.answers = {};
   }
   
   // checks for cached values
   if (isPrime.answers[value] !== undefined) {
      return isPrime.answers[value];
   }
   
   var prime = value !== 1; // is not a prime
   
   for (var i = 2; i < value; i++) {
      if (value % i === 0) {
         prime = false;
         break;
      }
   }
   
   return isPrime.answers[value] = prime;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment