Created
September 11, 2021 04:52
-
-
Save tjinlag/d03e79884cd36c6d83d98e5eb93025b0 to your computer and use it in GitHub Desktop.
memoize a function with an optional resolver to compute the proper key
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
const memoize = function(func, resolver) { | |
const cache = new Map(); | |
return (...args) => { | |
const key = resolver ? resolver.apply(this, args) : args[0]; | |
if (cache.has(key)) { | |
return cache.get(key); | |
} | |
const result = func.apply(this, args); | |
cache.set(key, result); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment