Skip to content

Instantly share code, notes, and snippets.

@digitalconceptvisuals
Last active July 29, 2020 22:02
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 digitalconceptvisuals/441d6a58fbb73d94ca5e430f9e044ea6 to your computer and use it in GitHub Desktop.
Save digitalconceptvisuals/441d6a58fbb73d94ca5e430f9e044ea6 to your computer and use it in GitHub Desktop.
// 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, mru=10) => new Proxy(fn,
// Handler with traps
{
// Instead of object, let's use a list which contains
// [ {args:2, result:true}, {args:3, result:true}, {args:4, result:false} ]
cache: [],
max: mru, // Our cache limit
// Our "magic" property
get(object, property, receiver) {
if (property == "cache")
return this.cache;
return Reflect.get(object, property, receiver);
},
// Intercept call to the wrapped function
apply(target, thisArg, args) {
// Scan the list to see if we have args cached
let exists = this.cache.find(element => {
element.args == args.toString();
});
// If exists, return the result
if (exists) {
result = exists.result;
} else {
// New result, store it at the end
result = Reflect.apply(target, thisArg, args);
this.cache.push({ args: args.toString(), result: result });
}
// Have we exceeded the limit? Drop the first element
if (this.cache.length > this.max)
this.cache.shift();
return result;
}
}
);
// Create the proxy and go thru max numbers to test for isPrime
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}`);
// Let's test 2 again
console.log("2 is prime", smartPrime(2));
console.log(`Cache size: ${smartPrime.cache.length}`);
console.log('Cache:', smartPrime.cache);
/* Output
Number of primes between 0 and 1000000: 78498
2 is prime true
Cache size: 10
Cache: [
{ args: '999992', result: false },
{ args: '999993', result: false },
{ args: '999994', result: false },
{ args: '999995', result: false },
{ args: '999996', result: false },
{ args: '999997', result: false },
{ args: '999998', result: false },
{ args: '999999', result: false },
{ args: '1000000', result: false },
{ args: '2', result: true }
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment