/* eslint-disable @typescript-eslint/no-explicit-any */
// Minimal promise-concurrency limiter (functional)

export function pLimit(concurrency: number) {
    let active = 0;
    const queue: Array<() => void> = [];

    function next() {
        active--;
        if (queue.length > 0) {
            const run = queue.shift()!;
            run();
        }
    }

    return function runLimited<T>(task: () => Promise<T>): Promise<T> {
        return new Promise<T>((resolve, reject) => {
            const run = () => {
                active++;
                task().then(resolve, reject).finally(next);
            };
            if (active < concurrency) run();
            else queue.push(run);
        });
    };
}