Last active
January 15, 2021 18:37
-
-
Save dehypnosis/03ca8cf64a704b18651f3dde4f8d2fe2 to your computer and use it in GitHub Desktop.
js memorize function
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
// memorization for performance; don't use this for mutable function | |
function memorize(fun) { | |
const cache = {}; | |
return function(){ | |
const args = Array.prototype.slice.call(arguments); | |
const key = JSON.stringify(args); | |
// fetch | |
let hit = cache[key]; | |
if (typeof hit != 'undefined') { | |
return typeof hit == 'object' && hit !== null | |
? JSON.parse(JSON.stringify(hit)) | |
: hit | |
} | |
// put | |
let result = fun.apply(this, args); | |
cache[key] = result; | |
setTimeout(() => { delete cache[key]; }, 3600000); // ttl is 1 hour | |
return typeof result == 'object' && result !== null | |
? JSON.parse(JSON.stringify(result)) | |
: result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage
in practice
caveat