"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Semaphore = void 0;
class Semaphore {
    constructor(maxConcurrency) {
        this.maxConcurrency = maxConcurrency;
        this.currentCount = 0;
        this.queue = [];
    }
    async acquire(task) {
        return new Promise((resolve, reject) => {
            this.queue.push({ task, resolve, reject });
            this.tryNext();
        });
    }
    tryNext() {
        if (this.currentCount < this.maxConcurrency && this.queue.length > 0) {
            this.currentCount++;
            const { task, resolve, reject } = this.queue.shift();
            task()
                .then(resolve)
                .catch(reject)
                .finally(() => {
                this.currentCount--;
                this.tryNext();
            });
        }
    }
}
exports.Semaphore = Semaphore;
//# sourceMappingURL=semaphore.js.map