Skip to content

Instantly share code, notes, and snippets.

@freddi301
Last active October 25, 2019 13:49
Show Gist options
  • Save freddi301/1d1b5219484473ce247f53d762265c1f to your computer and use it in GitHub Desktop.
Save freddi301/1d1b5219484473ce247f53d762265c1f to your computer and use it in GitHub Desktop.
Typescript call by need aka lazy
export type Lazy<Value> = () => Value
export function lazy<Value>(thunk: () => Value){
let value: Value // will hold computed value
let factory: (() => Value) | null = thunk // used as check if value is computed and allow thunk to be garbage collected
return () => {
if (!factory) {
return value
} else {
value = factory()
factory = null
return value
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment