aboutsummaryrefslogtreecommitdiff
path: root/2022/16-proboscidea-volcanium/priority_queue.js
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--2022/16-proboscidea-volcanium/priority_queue.js36
1 files changed, 10 insertions, 26 deletions
diff --git a/2022/16-proboscidea-volcanium/priority_queue.js b/2022/16-proboscidea-volcanium/priority_queue.js
index c1a5b65..b9be08b 100644
--- a/2022/16-proboscidea-volcanium/priority_queue.js
+++ b/2022/16-proboscidea-volcanium/priority_queue.js
@@ -6,50 +6,34 @@ export class QElement {
}
export class PriorityQueue {
- constructor() {
+ constructor(elt) {
this.items = [];
+ if (elt !== undefined) {
+ this.enqueue(elt, 0);
+ }
}
enqueue(element, priority) {
- var qElement = new QElement(element, priority);
- var contain = false;
+ let qElement = new QElement(element, priority);
- for (var i = 0; i < this.items.length; i++) {
+ for (let i = 0; i < this.items.length; ++i) {
if (this.items[i].priority > qElement.priority) {
this.items.splice(i, 0, qElement);
- contain = true;
- break;
+ return;
}
}
- if (!contain) {
- this.items.push(qElement);
- }
+ this.items.push(qElement);
}
dequeue() {
- if (this.isEmpty()){
- throw "Attempting to dequeue an empty queue";
- }
- return this.items.shift();
+ return this.items.shift(); // pop highest priority, use shift() for lower priority
}
front() {
- if (this.isEmpty()){
- throw "Attempting to front an empty queue";
- }
return this.items[0];
}
rear() {
- if (this.isEmpty()){
- throw "Attempting to rear an empty queue";
- }
return this.items[this.items.length - 1];
}
isEmpty() {
- return this.items.length == 0;
- }
- printPQueue() {
- var str = "";
- for (var i = 0; i < this.items.length; i++)
- str += this.items[i].element + " ";
- return str;
+ return this.items.length === 0;
}
}