whale-plus
Version:
A Component Library for Vue 3
81 lines (76 loc) • 1.62 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var EventEmitter = require('./EventEmitter.js');
class Task {
constructor(fn, payload) {
this.fn = fn;
this.payload = payload;
}
run() {
return this.fn(this.payload);
}
}
class TaskQueue extends EventEmitter.EventEmitter {
constructor(concurrency = 4) {
super();
this.tasks = /* @__PURE__ */ new Set();
this.currentCount = 0;
this.status = "paused";
this.concurrency = 4;
this.concurrency = concurrency;
}
add(...tasks) {
for (const t of tasks) {
this.tasks.add(t);
}
}
addAndStart(...tasks) {
this.add(...tasks);
this.start();
}
start() {
if (this.status === "running") {
return;
}
if (this.tasks.size === 0) {
this.emit("drain");
return;
}
this.status = "running";
this.emit("start");
this.runNext();
}
takeHeadTask() {
const task = this.tasks.values().next().value;
if (task) {
this.tasks.delete(task);
}
return task;
}
runNext() {
if (this.status !== "running") {
return;
}
if (this.currentCount >= this.concurrency) {
return;
}
const task = this.takeHeadTask();
if (!task) {
this.status = "paused";
this.emit("drain");
return;
}
this.currentCount++;
Promise.resolve(task.run()).finally(() => {
this.currentCount--;
this.runNext();
});
}
pause() {
this.status = "paused";
this.emit("pause");
}
}
exports.Task = Task;
exports.TaskQueue = TaskQueue;
//# sourceMappingURL=TaskQueue.js.map