Skip to content

Instantly share code, notes, and snippets.

@digitalconceptvisuals
Last active July 29, 2020 19:55
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/8813597c120a92488f51560f0a82828f to your computer and use it in GitHub Desktop.
Save digitalconceptvisuals/8813597c120a92488f51560f0a82828f 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) {
console.log(`Looped ${div} times`);
return false;
}
console.log(`Looped ${div} times`);
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: {},
// Intercept call to the wrapped function
apply(target, thisArg, args) {
// Do we have result in Proxy itself?
if (!(args in this.cache))
this.cache[args] = Reflect.apply(target, thisArg, args);
return this.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)}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment