Created
July 31, 2019 09:45
-
-
Save codeepic/cac9aeb1e49a35af0e28094b420ccec3 to your computer and use it in GitHub Desktop.
Memoize - function that memoizes other functions.
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
/** | |
* @param fn - a pure (no side effects) function you want to memoize | |
* if you run a memoized function again with the same arguments, | |
* it will return the cached result instead of running the computation | |
*/ | |
const memoize = fn => { | |
const cache = {}; | |
return (...args) => { | |
const key = JSON.stringify(args); | |
if (key in cache) { | |
return cache[key]; | |
} else { | |
const result = fn(...args); | |
cache[key] = result; | |
return result; | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment