-
Notifications
You must be signed in to change notification settings - Fork 108
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Replacing 'await-semaphore' since we need the `test()` function and there does not appear to be a widely used/maintained semaphore implementation that provides it and doesn't also depend on the `async/await` keywords at runtime.
- Loading branch information
Showing
7 changed files
with
4,870 additions
and
21 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
'use strict'; | ||
|
||
module.exports = exports = semaphore; | ||
|
||
function semaphore (count) { | ||
const resolvers = []; | ||
let counter = count; | ||
|
||
let sem = { | ||
take, | ||
release, | ||
test | ||
}; | ||
|
||
Object.defineProperty(sem, 'count', { | ||
get: _ => counter, | ||
enumerable: true | ||
}); | ||
|
||
return sem; | ||
|
||
function take (timeout) { | ||
if (counter > 0) { | ||
--counter; | ||
return Promise.resolve(release); | ||
} | ||
return new Promise((resolve, reject) => { | ||
resolvers.push(_ => { | ||
--counter; | ||
resolve(release); | ||
}); | ||
if (timeout) { | ||
setTimeout(_ => { | ||
resolvers.shift(); | ||
const err = new Error(`Timed out after ${timeout}ms`); | ||
err.code = 'ETIMEDOUT'; | ||
reject(err); | ||
}, timeout); | ||
} | ||
}); | ||
} | ||
|
||
function release () { | ||
counter++; | ||
if (resolvers.length > 0) { | ||
resolvers.shift()(); | ||
} | ||
} | ||
|
||
function test () { | ||
if (counter < 1) return false; | ||
return take() && true; | ||
} | ||
} |
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
Oops, something went wrong.