Created
August 22, 2018 19:29
-
-
Save sseletskyy/b4c2f9dd263ebfe92c81a0e0f399f6e4 to your computer and use it in GitHub Desktop.
Memoization example
This file contains 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
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