Created
April 17, 2021 03:53
-
-
Save AlexMercedCoder/b68a3a78dfac7e90448baeda985870b6 to your computer and use it in GitHub Desktop.
example of memoization in javascript
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
//////////////////////////////////// | |
// Example of Memoization by Alex Merced of AlexMercedCoder.com | |
/////////////////////////////////// | |
const addNums = (x,y) => x + y | |
const createMemo = (thefunc) => { | |
const cache = {} | |
return (...args) => { | |
console.time("memo") | |
const argstring = args.toString() | |
if(cache[argstring]){ | |
console.log("use cache") | |
console.timeEnd("memo") | |
return cache[argstring] | |
} else { | |
console.log("use function") | |
cache[argstring] = thefunc(...args) | |
console.timeEnd("memo") | |
return cache[argstring] | |
} | |
} | |
} | |
const memoAddNums = createMemo(addNums) | |
console.log(memoAddNums(1,1)) | |
console.log(memoAddNums(1,1)) | |
console.log(memoAddNums(1,1)) | |
console.log(memoAddNums(1,2)) | |
console.log(memoAddNums(1,2)) | |
console.log(memoAddNums(1,2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment