Skip to content

Instantly share code, notes, and snippets.

@nwellis
Created February 7, 2022 19:17
Show Gist options
  • Save nwellis/ed88ec8080ba173ba75d35fdeb4da468 to your computer and use it in GitHub Desktop.
Save nwellis/ed88ec8080ba173ba75d35fdeb4da468 to your computer and use it in GitHub Desktop.
export type Lazy<T, TArgs = void> = {
isInitialized(): boolean
get(args: TArgs): T
update(data: T)
clear(): Lazy<T>
}
export const lazy = <T, TArgs = void>(loader: (args: TArgs) => T) => {
let initialized = false
let lazy: T | undefined
return {
isInitialized: () => initialized,
get: (args: TArgs) => {
if (lazy) return lazy
initialized = true
lazy = loader(args)
return lazy
},
clear: () => {
lazy = undefined
initialized = false
},
update: (data: T) => {
lazy = data
initialized = true
}
} as Lazy<T, TArgs>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment