UNPKG

channel-ts

Version:

Channels implemented in Typescript using async/await

40 lines (39 loc) 1.02 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Guard = exports.Mutex = void 0; class Mutex { constructor() { this.resolveList = []; this.locked = [false]; } acquire() { return new Promise((resolve) => { if (!this.locked[0]) { this.locked[0] = true; // eslint-disable-next-line @typescript-eslint/no-use-before-define const guard = new Guard(this.resolveList, this.locked); resolve(guard); } else { this.resolveList.push(resolve); } }); } } exports.Mutex = Mutex; class Guard { constructor(lockList, locked) { this.resolveList = lockList; this.locked = locked; } release() { const resolve = this.resolveList.shift(); if (resolve) { resolve(this); } else { this.locked[0] = false; } } } exports.Guard = Guard;