UNPKG

@studiometa/js-toolkit

Version:

A set of useful little bits of JavaScript to boost your project! 🚀

72 lines (71 loc) • 1.36 kB
class Queue { /** * List of tasks. */ tasks = []; /** * Number of tasks running in a single batch. */ concurrency = 10; /** * A function to schedule the next batch. */ waiter; /** * Is schedule running? */ isScheduled = false; /** * Constructor. * * @param {number} concurrency Number of tasks running in a single batch. * @param {(cb: (...args:unknown[]) => unknown) => unknown} waiter Scheduler for the next batch execution. */ constructor(concurrency, waiter = (cb) => cb()) { this.concurrency = concurrency; this.waiter = waiter; } /** * Add a task to the queue. */ add(task) { const p = new Promise((resolve) => { this.tasks.push(() => resolve(task())); }); this.scheduleFlush(); return p; } /** * Schedule next flush. */ scheduleFlush() { if (this.isScheduled) { return; } this.isScheduled = true; this.waiter(() => this.flush()); } /** * Flush current batch. */ flush() { this.run(this.tasks.splice(0, this.concurrency)); this.isScheduled = false; if (this.tasks.length > 0) { this.scheduleFlush(); } } /** * Run the queue. */ run(tasks) { let task; while (task = tasks.shift()) { task(); } } } export { Queue }; //# sourceMappingURL=Queue.js.map