-
Notifications
You must be signed in to change notification settings - Fork 2
/
queue.js
57 lines (44 loc) · 950 Bytes
/
queue.js
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
class Queue {
#queue
#start
#end
constructor (elements = []) {
if (!Array.isArray(elements)) throw Error('Invalid queue constructor')
this.#queue = {}
this.#start = 0
this.#end = elements.length
this.#buildQueue(this.#queue, elements)
}
enqueue (element) {
this.#queue[this.#end++] = element
}
dequeue () {
if (this.isEmpty) return undefined
const element = this.peek()
delete this.#queue[this.#start++]
return element
}
peek () {
return this.#queue[this.#start]
}
clear () {
this.#queue = {}
this.#start = 0
this.#end = 0
}
get isEmpty () {
return this.#end - this.#start === 0
}
get length () {
return this.#end - this.#start
}
#buildQueue (queue, elements) {
for (let i = 0; i < elements.length; i++) {
queue[i] = elements[i]
}
}
toString () {
return Object.values(this.#queue).join()
}
}
export default Queue