Last active
October 25, 2019 13:49
-
-
Save freddi301/1d1b5219484473ce247f53d762265c1f to your computer and use it in GitHub Desktop.
Typescript call by need aka lazy
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<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