-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.ts
76 lines (57 loc) · 1.27 KB
/
index.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
69
70
71
72
73
74
75
76
export interface Queue<T> {
items: T[];
maximum: number;
head: number;
tail: number;
peek(): T;
enqueue(item: T): void;
dequeue(): void;
}
export class Queue<T> implements Queue<T> {
items: T[];
maximum: number;
head: number;
tail: number;
size: number;
constructor(size: number = Math.pow(2, 32)) {
this.items = new Array(size - 1);
this.maximum = size;
this.head = 0;
this.tail = -1;
this.size = 0;
}
peek(): T {
return this.items[this.head];
}
enqueue(item: T) {
if (this.size === this.maximum) {
throw Error("Overflow error");
}
this.tail = (this.tail + 1) % this.maximum;
console.log(`Enqueuing #${this.tail}`);
this.items[this.tail] = item;
console.log(`Tail #${this.tail}`);
this.size++;
}
dequeue() {
if (!this.size) {
throw Error("Underflow error");
}
console.log(`Dequeuing #${this.head}`);
// Circular
this.head = (this.head + 1) % this.maximum;
console.log(`Head #${this.head}`);
this.size--;
}
}
// const n = 64;
// const queue = new Queue<number>(n);
// for (let i = 0; i < n; i++) {
// queue.enqueue(i);
// }
// for (let i = 0; i < n / 2; i++) {
// queue.dequeue();
// }
// console.log(queue);
// // 32
// console.log(queue.peek());