Created
February 7, 2022 19:17
-
-
Save nwellis/ed88ec8080ba173ba75d35fdeb4da468 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
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