Created
January 24, 2019 20:27
-
-
Save ardenn/ce3e881d1030711265f1950fc1453cd8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// A function that returns true if a number is prime | |
function isPrime(num) { | |
let numIsPrime = true; | |
if (num === 1) { | |
return false; | |
} | |
for (let i = 2; i < num; i++) { | |
if (num % i === 0) { | |
numIsPrime = false; | |
console.log(i); | |
break | |
} | |
} | |
return numIsPrime | |
} | |
// console.log(isPrime(157)) | |
// A function that returns a memoized version of any other function | |
function memorize(func) { | |
let resultsCache = {}; | |
return (num) => { | |
if (num in resultsCache) { | |
console.log("Reading from cache..."); | |
return resultsCache[num]; | |
} | |
console.log("Running function..."); | |
let result = func(num); | |
resultsCache[num] = result; | |
return result; | |
} | |
} | |
const memoizedPrime = memorize(isPrime); | |
console.log(memoizedPrime(157)) | |
console.log(memoizedPrime(157)) | |
console.log(memoizedPrime(157)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment