-
-
Save digitalconceptvisuals/817d861769e733c775e64fa07a358a9c 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) | |
return false; | |
return true; | |
} | |
// Memoize is a Proxy to the actual function | |
const memoize = fn => new Proxy(fn, | |
// Handler with traps | |
{ | |
// We store previous results here | |
cache: {}, | |
get(object, property, receiver) { | |
if (property == "length") | |
return Object.keys(this.cache).length; | |
}, | |
// Intercept call to the wrapped function | |
apply(target, thisArg, args) { | |
if (!(args in this.cache)) | |
this.cache[args] = Reflect.apply(target, thisArg, args); | |
return this.cache[args]; | |
} | |
} | |
); | |
// This is a known prime | |
let smartPrime = memoize(isPrime); | |
let max = 1000000; | |
let primeCount = 0; | |
for (let number = 2; number <= max; number++) | |
if (smartPrime(number)) { | |
primeCount++; | |
} | |
console.log(`Number of primes between 0 and ${max}: ${primeCount}`); | |
console.log(`Cache memory: ${smartPrime.length}`); | |
/* Ouput | |
Number of primes between 0 and 1000000: 78498 | |
Cache memory: 999999 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment