-
Notifications
You must be signed in to change notification settings - Fork 0
/
PriorityQueue.js
79 lines (55 loc) · 1.35 KB
/
PriorityQueue.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const Sort = require("../Sort")
class PriorityQueue extends Sort {
#itemsCount
#items
constructor() {
super()
this.#itemsCount = 0
this.#items = []
}
delMax() {
const maxPriorityItem = this.max()
this.#items.splice(0, 1)
this.#itemsCount--
return maxPriorityItem
}
max() {
const isEmpty = this.isEmpty()
if (isEmpty) {
throw new Error("This PriorityQueue is empty!")
}
const maxPriorityItem = this.#items[0]
return maxPriorityItem
}
insert(item) {
let insertionIndex = 0
/**
* Insert items in a descending ordered format
*/
for (let rightScanIndex = this.size() - 1; rightScanIndex !== -1; rightScanIndex--) {
const currentItem = this.#items[rightScanIndex]
const isFirstValueLowerThanSecondValue = this.isFirstValueLowerThanSecondValue(currentItem, item)
if (isFirstValueLowerThanSecondValue) {
insertionIndex = rightScanIndex
} else {
break
}
}
this.#items.splice(insertionIndex, 0, item)
this.#itemsCount++
}
isEmpty() {
const isEmpty = this.#itemsCount === 0
return isEmpty
}
size() {
const size = this.#itemsCount
return size
}
*[Symbol.iterator]() {
for(let item = this.delMax(); !this.isEmpty(); item = this.delMax()) {
yield item
}
}
}
module.exports = PriorityQueue