Skip to content

Instantly share code, notes, and snippets.

@isiahmeadows isiahmeadows/lazy.js
Created Aug 31, 2017

What would you like to do?
Lazy class
* 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
throw this.value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.