This repository has been archived by the owner on Dec 4, 2023. It is now read-only.
/
queue.ts
93 lines (85 loc) · 2.67 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import LinkedList from '../linked-list'
import * as utils from '../../utils'
class Queue<T> implements Iterable<T> {
private list: LinkedList<T>
constructor(equalsFunction?: utils.EqualsFunction<T>) {
if (equalsFunction) this.list = new LinkedList(equalsFunction)
else this.list = new LinkedList()
}
/*****************************************************************************
INSPECTION
*****************************************************************************/
/**
* Returns size of queue - O(1)
*/
size(): number {
return this.list.size()
}
/**
* Returns true if queue is empty, false otherwise - O(1)
*/
isEmpty(): boolean {
return this.list.isEmpty()
}
/**
* Deletes all elements in queue - O(1)
*/
clear(): void {
this.list.clear()
}
/*****************************************************************************
INSERTION/DELETION
*****************************************************************************/
/**
* Enqueues element into queue - O(1)
* @param {T} element - element to be enqueued
*/
enqueue(element: T): void {
this.list.addFront(element)
}
/**
* Dequeues element from queue - O(1)
* @returns {T}
*/
dequeue(): T | null {
if (this.isEmpty()) return null
return this.list.removeBack()
}
/*****************************************************************************
ACCESSING
*****************************************************************************/
/**
* Peeks at the element at the front of the queue - O(1)
* @returns {T} - Frontmost element
*/
peekFront(): T | null {
if (this.isEmpty()) return null
return this.list.peekBack()
}
/**
* Peeks at the element at the back of the queue - O(1)
* @returns {T} - Backmost element
*/
peekBack(): T | null {
if (this.isEmpty()) return null
return this.list.peekFront()
}
/*****************************************************************************
SEARCHING
*****************************************************************************/
/**
* Checks if value is in queue - O(n)
* @param {T} element - element to search for
* @returns {boolean}
*/
contains(element: T): boolean {
return this.list.contains(element)
}
/*****************************************************************************
HELPERS
*****************************************************************************/
[Symbol.iterator](): Iterator<T> {
return this.list[Symbol.iterator]()
}
}
export default Queue