NPM Function-memoizer
// get the memoize function
const memoize = require("function-memoizer");
// demonstration function (returns whether or not a number is prime)
function isPrime(n) {
if (typeof n !== "number") throw TypeError();
if (n !== Math.round(n)) return false;
if (n < 2) return false;
if (n < 4) return true;
if (n < 10) return n === 5 || n === 7;
for (let i = 11; i * i < n; i++) if (n % i === 0) return false;
return true;
}
// memoize isPrime and store it as a new function named memoizedIsPrime
let memoizedIsPrime = memoize(isPrime);
// get the number of iterations to run
let numberOfIterations = parseInt(prompt("Enter the number of iterations to perform "));
// record the start time
let startTime = Date.now(), originalTime;
// run iterations
for (let i = 0; i < numberOfIterations; i++) memoizedIsPrime(i);
// print the time taken
console.log("Total milleseconds for primes under " + numberOfIterations + ": " + (originalTime = Date.now() - startTime) + "ms");
// record the start time
startTime = Date.now();
let secondTime;
// run iterations
for (let i = 0; i < numberOfIterations; i++) memoizedIsPrime(i);
// print the time taken
console.log("Total milleseconds for primes under " + numberOfIterations + ": " + (secondTime = Date.now() - startTime) + "ms");
// print time difference
console.log("The second time ran ~" + Math.round(originalTime / secondTime) + "x faster");
MattDESTROYER