export function pLimit(concurrency) {
    if (!Number.isInteger(concurrency) || concurrency < 1) {
        throw new Error(`pLimit: concurrency must be a positive integer, got ${concurrency}`);
    }
    let active = 0;
    const queue = [];
    const next = () => {
        active--;
        const resume = queue.shift();
        if (resume)
            resume();
    };
    return (fn) => new Promise((resolve, reject) => {
        const run = () => {
            active++;
            fn().then((value) => { resolve(value); next(); }, (error) => { reject(error); next(); });
        };
        if (active < concurrency)
            run();
        else
            queue.push(run);
    });
}
