UNPKG

@beenotung/tslib

Version:
45 lines (44 loc) 1.15 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Lock = void 0; exports.createLock = createLock; const defer_1 = require("./async/defer"); class Lock { quota; res; queue = []; constructor(quota = 1) { this.quota = quota; this.res = quota; } async acquire(amount = 1) { if (amount > this.quota) { throw new Error('not enough quota: max=' + this.quota + ', require=' + amount); } if (this.res >= amount) { this.res -= amount; return; } const defer = (0, defer_1.createDefer)(); this.queue.push({ defer, amount }); return defer.promise; } release(amount = 1) { this.res += amount; this.check(); } check() { this.queue = this.queue.filter(item => { if (this.res >= item.amount) { this.res -= item.amount; item.defer.resolve(void 0); return false; } return true; }); } } exports.Lock = Lock; function createLock(quota = 1) { return new Lock(quota); }