Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

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");
Comment

PREVIOUS NEXT
Code Example
Javascript :: ngswitch example on string 
Javascript :: get page scrolling amount js 
Javascript :: get biggest element in array javascript 
Javascript :: change rotation phaser 
Javascript :: reactjs libphonenumber 
Javascript :: phaser grid align 
Javascript :: phaser random triangle 
Javascript :: regex to allow special characters 
Javascript :: phaser animation on update event 
Javascript :: How to call the API when the search value changes 
Javascript :: swr vs axios 
Javascript :: template literal inside a key in react 
Javascript :: Expresion regular para validar contraseñas 
Javascript :: javascript search an array of json for matching attribute 
Javascript :: iterate over array of html elements 
Javascript :: golang read json file 
Javascript :: how to print in html 
Javascript :: change text color according to background js 
Javascript :: js filter example 
Javascript :: regex and 
Javascript :: what is closures in javascript 
Javascript :: SELECT * FROM USERSs 
Javascript :: for loop in js 
Javascript :: Material-ui account circle icon 
Javascript :: using for loops js 
Javascript :: datatable change default sorting 
Javascript :: javascript eliminar saltos de linea textarea 
Javascript :: add 7 days in date using jquery 
Javascript :: react -native-config 
Javascript :: React_Weather_APp 
ADD CONTENT
Topic
Content
Source link
Name
2+9 =