Last active
January 7, 2022 16:35
-
-
Save doasync/9e206b55226147a48825e896c7094e9f to your computer and use it in GitHub Desktop.
Create cached function (memoize)
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
export const cached = (fn) => { | |
const cache = new Map(); | |
return function cachedFn(...args) { | |
const input = JSON.stringify(args); | |
if (cache.has(input)) { | |
return cache.get(input); | |
} | |
const result = fn.apply(this, args); | |
cache.set(input, result); | |
return result; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment