Last active
February 9, 2023 15:42
-
-
Save ken107/df6ac4d5f86ad96747f5c9a2d7374d73 to your computer and use it in GitHub Desktop.
A getter that calls generator() to create a new instance and subsequently returns the same instance while it isValid()
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 function makeValidGetter<T extends {isValid(): boolean}>(generator: () => Promise<T>): () => Promise<T> { | |
let value: T|undefined | |
let promise: Promise<T>|undefined | |
return async function() { | |
if (value?.isValid()) return value | |
if (promise) return await promise | |
promise = generator() | |
.then(result => { | |
value = result | |
promise = undefined | |
return value | |
}) | |
return await promise | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment