Created
April 6, 2019 16:30
-
-
Save atishay/12150b34c2294f12221da97d221932ab to your computer and use it in GitHub Desktop.
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
| function memoize(func, resolver) { | |
| const memoized = function(...args) { | |
| const key = resolver ? resolver.apply(this, args) : args[0] | |
| const cache = memoized.cache | |
| if (cache.has(key)) { | |
| return cache.get(key) | |
| } | |
| const result = func.apply(this, args) | |
| memoized.cache = cache.set(key, result) || cache | |
| return result | |
| } | |
| memoized.cache = new Map(); | |
| return memoized | |
| } | |
| // Usage | |
| let get = memoize(async (...args) => { | |
| ... | |
| return data; | |
| }); | |
| const A = async () => await get('x'); | |
| const B = async () => await get('x'); | |
| const C = async () => await get('y'); | |
| const D = async () => await get('x'); | |
| // A and B in parallel | |
| await Promise.all([A(), B(), C()]); | |
| // Get is finished already. | |
| await D(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment