-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.js
47 lines (43 loc) · 1.07 KB
/
queue.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
import { waitFor } from "./wait-for.js";
export class Queue {
#writeQueue = new Array();
#readQueue = new Array();
#capacity = 10;
constructor(capacity = 10) {
this.#capacity = capacity;
}
async write(msg) {
if (
await waitFor({
predicate: () => this.#writeQueue.length < this.#capacity,
errorMsg: "Write timeout",
})
) {
this.#writeQueue.push(msg);
}
}
async read() {
// wait for writeQueue to fill up if readQueue is empty
if (
this.#readQueue.length == 0 &&
(await waitFor({
predicate: () => this.#writeQueue.length > 0,
errorMsg: "Shift timeout",
}))
) {
// pop all elements from writeQueue and push them to readQueue
while (this.#writeQueue.length > 0) {
this.#readQueue.push(this.#writeQueue.pop());
}
}
// return last element from readQueue if non-empty
if (
await waitFor({
predicate: () => this.#readQueue.length > 0,
errorMsg: "Read timeout",
})
) {
return this.#readQueue.pop();
}
}
}