Skip to content

Instantly share code, notes, and snippets.

@sseletskyy
Created August 22, 2018 19:29
Show Gist options
  • Save sseletskyy/b4c2f9dd263ebfe92c81a0e0f399f6e4 to your computer and use it in GitHub Desktop.
Save sseletskyy/b4c2f9dd263ebfe92c81a0e0f399f6e4 to your computer and use it in GitHub Desktop.
Memoization example
function memoize(func) {
const map = new Map()
return function() {
const args = Array.prototype.slice.call(arguments)
const key = JSON.stringify(args)
if (! map.has(key)) map.set(key, func.apply(null, args))
return map.get(key)
}
}
// example to use
function add(a,b) {
function delayed() { return a + b }
for(let i=1e8; i > 0; i--) { delayed() }
return delayed()
}
const _add = memoize(add)
console.log(_add(3,4))
console.log(_add(3,5))
console.log(_add(3,4))
console.log(_add(3,5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment