Skip to content

Instantly share code, notes, and snippets.

@ken107
Last active February 9, 2023 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ken107/df6ac4d5f86ad96747f5c9a2d7374d73 to your computer and use it in GitHub Desktop.
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()
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