@beenotung/tslib
Version:
utils library in Typescript
46 lines • 1.34 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLock = exports.Lock = void 0;
const tslib_1 = require("tslib");
const defer_1 = require("./async/defer");
class Lock {
constructor(quota = 1) {
this.queue = [];
this.quota = quota;
this.res = quota;
}
acquire(amount = 1) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
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 = 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);
}
exports.createLock = createLock;
//# sourceMappingURL=lock.js.map