-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathqueue-printer-network.js
104 lines (86 loc) · 1.91 KB
/
queue-printer-network.js
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
class Queue {
#list = [];
#capacity = null;
constructor(capacity) {
this.#capacity = Math.max(Number(capacity), 0) || null;
}
get size() {
return this.#list.length;
}
get isEmpty() {
return this.size === 0;
}
get isFull() {
return this.#capacity !== null && this.size === this.#capacity;
}
enqueue(item) {
if (this.#capacity === null || this.size < this.#capacity) {
return this.#list.push(item);
}
return this.size;
}
dequeue() {
return this.#list.shift();
}
peek() {
return this.#list[0];
}
print() {
console.log(this.#list);
}
}
class Printer extends Queue {
#printing = false;
constructor() {
super(10);
this.id = Math.floor(Math.random() * 10000);
}
#printDocs = () => {
this.#printing = true;
setTimeout(() => {
const docCall = this.dequeue();
docCall();
if (this.isEmpty) {
this.#printing = false;
} else {
this.#printDocs();
}
}, Math.floor(Math.random() * 2000));
};
print(doc) {
return new Promise((res, rej) => {
if (this.isFull) {
rej("Printer is full");
} else {
this.enqueue(() => res(doc));
if (!this.#printing) {
this.#printDocs();
}
}
});
}
}
class PrinterNetwork extends Queue {
#printers = [new Printer(), new Printer(), new Printer()];
print(doc) {
return new Promise((res) => {
const freePrinter = this.#printers.reduce((acc, p) => {
if (p.size < acc.size) {
acc = p;
}
return acc;
}, this.#printers[0]);
if (freePrinter.isFull) {
this.enqueue(() => this.print(doc).then((id) => res(id)));
} else {
freePrinter.print(doc).then(() => {
res(freePrinter.id);
if (this.size) {
const nextDoc = this.dequeue();
nextDoc();
}
});
}
});
}
}