Skip to content

Instantly share code, notes, and snippets.

@AlexMercedCoder
Created April 17, 2021 03:53
Show Gist options
  • Save AlexMercedCoder/b68a3a78dfac7e90448baeda985870b6 to your computer and use it in GitHub Desktop.
Save AlexMercedCoder/b68a3a78dfac7e90448baeda985870b6 to your computer and use it in GitHub Desktop.
example of memoization in javascript
////////////////////////////////////
// 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