Last active
April 1, 2020 08:58
-
-
Save alexsasharegan/a523475ec403588b1036e3619039e4e3 to your computer and use it in GitHub Desktop.
Nodejs implementation of the Golang waitgroup.
This file contains 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
import { EventEmitter } from "events" | |
export class WaitGroup extends EventEmitter { | |
public state: number | |
constructor(initialState: number = 0) { | |
if (initialState < 0) { | |
throw new RangeError() | |
} | |
super() | |
this.state = initialState | |
} | |
public Add(delta: number = 1): number { | |
this.state += delta | |
if (this.state < 0) { | |
throw new RangeError() | |
} | |
this.emit("change", this.state) | |
if (this.state == 0) { | |
this.emit("done") | |
} | |
return this.state | |
} | |
public Done(): number { | |
return this.Add(-1) | |
} | |
Wait(): Promise<void> | |
Wait(cb: () => void): void | |
public Wait(cb?: () => void) { | |
// Handle when wait group is already drained. | |
if (this.state == 0) { | |
// Callback style | |
if (cb) { | |
return cb() | |
} | |
// Promise style | |
return Promise.resolve() | |
} | |
// Callback style | |
if (cb) { | |
this.once("done", cb) | |
return | |
} | |
// Promise style | |
return new Promise<void>(resolve => { | |
this.once("done", resolve) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment