-
Notifications
You must be signed in to change notification settings - Fork 10
/
MultiConnectionQueue.ts
53 lines (43 loc) · 1.37 KB
/
MultiConnectionQueue.ts
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
import { AsyncIterator } from "asynciterator";
import TinyQueue from "tinyqueue";
import IConnection from "../../../../entities/connections/connections";
export default class MultiConnectionQueue {
private closed: boolean;
private asyncIterator: AsyncIterator<IConnection>;
private queue: TinyQueue<IConnection>;
private next: IConnection;
constructor(asyncIterator: AsyncIterator<IConnection>) {
this.closed = false;
this.asyncIterator = asyncIterator;
this.queue = new TinyQueue([], (a, b) => {
return a.departureTime - b.departureTime;
});
}
public close() {
this.asyncIterator.close();
this.closed = true;
}
public isClosed(): boolean {
return this.closed || this.asyncIterator.closed;
}
public push(connection: IConnection) {
this.queue.push(connection);
}
public pop(): IConnection {
if (!this.asyncIterator.readable) {
return;
}
if (!this.next) {
this.next = this.asyncIterator.read();
}
if (!this.next) {
return this.queue.pop();
}
if (this.queue.peek() && this.queue.peek().departureTime < this.next.departureTime) {
return this.queue.pop();
}
const result = this.next;
this.next = undefined;
return result;
}
}