-
-
Save digitalconceptvisuals/a29eb483ace7fb46b7bd7396e54f6c33 to your computer and use it in GitHub Desktop.
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
// Check if given number is prime | |
const isPrime = number => { | |
if (number < 2) return false; | |
// Divide number by all numbers from 2 to sqrt(number) | |
// If divisible, then its not a prime | |
let div; | |
for (div = 2; div < Math.sqrt(number); div++) | |
if (number % div == 0) { | |
console.log(`Looped ${div} times`); | |
return false; | |
} | |
console.log(`Looped ${div} times`); | |
return true; | |
} | |
const memoize = fn => { | |
// We store previous results here | |
const cache = {}; | |
// Return a function to be called | |
return memoized = (...args) => { | |
// If result not in cache, first cache it | |
if (!(args in cache)) | |
cache[args] = fn(...args); | |
// Now return it | |
return cache[args]; | |
} | |
} | |
// This is a known prime | |
let number = 1299827; | |
const smartPrime = memoize(isPrime); | |
console.log(`${number} is prime: ${smartPrime(number)}`); | |
console.log(`${number} is prime: ${smartPrime(number)}`); | |
/* Output | |
Looped 1141 times | |
1299827 is prime: true | |
1299827 is prime: true | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment