-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.ts
More file actions
46 lines (39 loc) · 894 Bytes
/
queue.ts
File metadata and controls
46 lines (39 loc) · 894 Bytes
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
export {};
/**
* FIFO (first in first out)
*/
export interface Queue<T> {
enqueue(element: T): void;
dequeue(): T;
size(): number;
}
export class Queue<T> implements Queue<T> {
protected MAX_QUEUE_SIZE: number = 1000;
protected head: number = 0;
private storage: T[] = [];
constructor(MAX_QUEUE_SIZE?: number) {
if (typeof MAX_QUEUE_SIZE === "number") {
this.MAX_QUEUE_SIZE = MAX_QUEUE_SIZE;
}
}
enqueue(element: T): void {
if (this.size() < this.MAX_QUEUE_SIZE) {
this.storage.push(element);
} else {
throw new Error("Queue overflow!");
}
}
dequeue(): T {
const output = this.storage[this.head];
this.storage[this.head] = undefined as unknown as T;
this.head++;
if (this.head >= this.MAX_QUEUE_SIZE) {
this.storage.slice(0, this.head);
this.head = 0;
}
return output;
}
size(): number {
return this.storage.length - this.head;
}
}