Skip to content

Instantly share code, notes, and snippets.

@alexsasharegan
Created January 30, 2018 16:08
Show Gist options
  • Save alexsasharegan/bf697070ff0df3e18b791142244e5efd to your computer and use it in GitHub Desktop.
Save alexsasharegan/bf697070ff0df3e18b791142244e5efd to your computer and use it in GitHub Desktop.
function newWaitGroup(state = 0) {
const cbs = []
const wg = {}
function invoke() {
let cb
while ((cb = cbs.shift())) {
if (typeof cb != "function") {
throw new TypeError(
"A callback function should be passed to WaitGroup.wait()"
)
}
cb()
}
}
wg.add = function add(delta = 1) {
if (state + delta < 0) {
throw new RangeError()
}
state += delta
if (state == 0) {
invoke()
}
return state
}
wg.done = function done() {
wg.add(-1)
}
wg.wait = function wait(callback) {
cbs.push(callback)
}
return wg
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment