-
Notifications
You must be signed in to change notification settings - Fork 26
/
Queue.ts
68 lines (60 loc) · 1.13 KB
/
Queue.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
type Item<T> = {
next: Item<T> | null;
value: T;
};
export default class Queue<T> {
#head: Item<T> | null;
#length: number;
#tail: Item<T> | null;
/**
* Optionally takes an iterable of items with which to initially seed the queue.
*/
constructor(items?: Iterable<T>) {
this.#head = null;
this.#tail = null;
this.#length = 0;
if (items) {
for (const item of items) {
this.enqueue(item);
}
}
}
dequeue() {
const node = this.#head;
if (node) {
this.#head = node.next;
this.#length--;
if (this.#head === null) {
this.#tail = null;
}
return node.value;
} else {
return null;
}
}
enqueue(item: T) {
const node = {
next: null,
value: item,
};
if (this.#tail) {
this.#tail.next = node;
this.#tail = node;
} else {
this.#head = node;
this.#tail = node;
}
this.#length++;
}
isEmpty() {
return this.#length === 0;
}
get length() {
return this.#length;
}
*[Symbol.iterator]() {
while (!this.isEmpty()) {
yield this.dequeue()!;
}
}
}