Created
January 30, 2018 16:08
-
-
Save alexsasharegan/bf697070ff0df3e18b791142244e5efd to your computer and use it in GitHub Desktop.
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
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