-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
queue.ts
74 lines (68 loc) · 1.42 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
69
70
71
72
73
74
// Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
/**
* Queue
*
* @typeParam T - Type of queue items.
*/
export class Queue<T> {
private items!: T[]
private offset!: number
/** The size of the queue. */
public size!: number
/** The maximum size of the queue. */
public maxSize!: number
public constructor () {
this.clear()
}
/**
* Enqueue an item.
*
* @param item - Item to enqueue.
* @returns The new size of the queue.
*/
public enqueue (item: T): number {
this.items.push(item)
++this.size
if (this.size > this.maxSize) {
this.maxSize = this.size
}
return this.size
}
/**
* Dequeue an item.
*
* @returns The dequeued item or `undefined` if the queue is empty.
*/
public dequeue (): T | undefined {
if (this.size <= 0) {
return undefined
}
const item = this.items[this.offset]
if (++this.offset * 2 >= this.items.length) {
this.items = this.items.slice(this.offset)
this.offset = 0
}
--this.size
return item
}
/**
* Peeks at the first item.
*
* @returns The first item or `undefined` if the queue is empty.
*/
public peek (): T | undefined {
if (this.size <= 0) {
return undefined
}
return this.items[this.offset]
}
/**
* Clears the queue.
*/
public clear (): void {
this.items = []
this.offset = 0
this.size = 0
this.maxSize = 0
}
}