-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4.taskQueue.js
More file actions
77 lines (66 loc) · 1.64 KB
/
Copy path4.taskQueue.js
File metadata and controls
77 lines (66 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import logUpdate from "log-update";
const delay = (seconds) =>
new Promise((resolve) => {
setTimeout(() => resolve(`waited ${seconds} seconds...`), seconds * 1000);
});
class Task {
constructor(task = (f) => f, args = []) {
this.task = (...args) => Promise.resolve(task(...args));
this.args = args;
}
execute() {
return new Promise((resolve, reject) => {
this.task(...this.args).then(resolve);
});
}
}
class TaskQueue {
constructor(tasks = [], concurrentCount = 1) {
this.tasks = tasks;
this.concurrentCount = concurrentCount;
this.running = [];
this.completed = [];
this.failed = [];
}
get hasTasks() {
return this.running.length < this.concurrentCount && this.tasks.length > 0;
}
logTasks() {
const toX = () => "x";
const { tasks, running, completed } = this;
logUpdate(`
Tasks: [${tasks.map(toX)}]
Running: [${running.map(toX)}]
Completed: [${completed.map(toX)}]
`);
}
run() {
while (this.hasTasks) {
const task = this.tasks.shift();
task.execute().then((result) => {
this.running.shift();
this.completed.push(result);
this.logTasks();
this.run();
});
this.running.push(task);
this.logTasks();
}
}
}
const tasks = [
new Task(delay, [3]),
new Task(console.log, [100]),
new Task(delay, [10]),
new Task(delay, [4]),
new Task(delay, [1]),
new Task(delay, [6]),
new Task(delay, [7]),
new Task(delay, [2]),
new Task(delay, [11]),
new Task(delay, [8]),
new Task(delay, [5]),
new Task(delay, [7]),
];
const taskQueue = new TaskQueue(tasks, 3);
taskQueue.run();