Repository navigation
Expand file tree
/
Copy pathqueue.ts
More file actions
75 lines (65 loc) · 2.12 KB
/
Copy pathqueue.ts
File metadata and controls
75 lines (65 loc) · 2.12 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
/**
* Queue (first in, first out) backed by a growable ring buffer
*
* Idea: `Array.prototype.shift` is O(n) because every element moves down one
* slot. A ring buffer avoids that: keep a fixed array, an index of the front
* element and a count. Enqueue writes at `(head + count) % capacity`, dequeue
* reads at `head` and moves `head` forward, wrapping around the end. When the
* buffer is full, copy everything into an array twice as large.
*
* Used for: breadth-first search, task scheduling, rate limiting, buffering
* streams.
*
* Complexity: enqueue O(1) amortized, dequeue / peek O(1); space O(n).
*/
export class Queue<T> implements Iterable<T> {
private buffer: (T | undefined)[];
private head = 0;
private count = 0;
constructor(initialCapacity = 8) {
this.buffer = new Array<T | undefined>(Math.max(1, Math.floor(initialCapacity)));
}
get size(): number {
return this.count;
}
/** Current slot count of the underlying buffer (useful for learning). */
get capacity(): number {
return this.buffer.length;
}
isEmpty(): boolean {
return this.count === 0;
}
enqueue(value: T): this {
if (this.count === this.buffer.length) this.grow();
this.buffer[(this.head + this.count) % this.buffer.length] = value;
this.count++;
return this;
}
dequeue(): T | undefined {
if (this.count === 0) return undefined;
const value = this.buffer[this.head];
this.buffer[this.head] = undefined; // let the garbage collector reclaim it
this.head = (this.head + 1) % this.buffer.length;
this.count--;
return value;
}
peek(): T | undefined {
return this.count === 0 ? undefined : this.buffer[this.head];
}
toArray(): T[] {
return [...this];
}
*[Symbol.iterator](): Iterator<T> {
for (let i = 0; i < this.count; i++) {
yield this.buffer[(this.head + i) % this.buffer.length] as T;
}
}
private grow(): void {
const next = new Array<T | undefined>(this.buffer.length * 2);
for (let i = 0; i < this.count; i++) {
next[i] = this.buffer[(this.head + i) % this.buffer.length];
}
this.buffer = next;
this.head = 0;
}
}