Skip to content

Instantly share code, notes, and snippets.

@arabold
Created July 18, 2020 14:18
Show Gist options
  • Save arabold/01c3d150376e3e6953785be9cdf3c6f1 to your computer and use it in GitHub Desktop.
Save arabold/01c3d150376e3e6953785be9cdf3c6f1 to your computer and use it in GitHub Desktop.
export type SemaphoreFunction = (done: () => void) => void;
/**
* Based on https://www.derpturkey.com/simple-semaphore-in-nodejs/
*/
export default class Semaphore {
readonly max: number;
private _fns: Array<SemaphoreFunction>;
private _active: number;
constructor(max: number = 1) {
this.max = max;
this._fns = [];
this._active = 0;
}
get remaining() {
return this._fns.length;
}
get active() {
return this._active;
}
take(fn: SemaphoreFunction) {
this._fns.push(fn);
this._try();
}
private _done() {
this._active -= 1;
this._try();
}
private _try(): boolean {
if (this._active === this.max || this._fns.length === 0) {
return false;
}
const fn = this._fns.shift();
this._active += 1;
fn?.(this._done.bind(this));
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment