Created
August 31, 2017 13:04
-
-
Save dead-claudia/4c0723bdfa555a1c2cb01341b323c3d4 to your computer and use it in GitHub Desktop.
Lazy class
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
/** | |
* A lazy value that also memoizes exceptions and checks for recursion. | |
*/ | |
export class Lazy { | |
constructor(init) { | |
this.state = State.Init | |
this.value = init | |
} | |
// This shouldn't count against the inline quota. | |
_init() { | |
this.state = State.Invoke | |
try { | |
this.value = (0, this.value)() | |
this.state = State.Return | |
return this.value | |
} catch (e) { | |
this.value = e | |
this.state = State.Throw | |
throw this.value | |
} | |
} | |
get() { | |
switch (this.state) { | |
case State.Init: | |
return this._init() | |
case State.Invoke: | |
throw new TypeError("Invalid recursive read of lazy value") | |
case State.Return: | |
return this.value | |
default: | |
throw this.value | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment