advent-of-code/2022/16-proboscidea-volcanium/priority_queue.js

40 lines
768 B
JavaScript
Raw Normal View History

2022-12-26 07:48:55 +01:00
export class QElement {
constructor(element, priority) {
this.element = element;
this.priority = priority;
}
}
export class PriorityQueue {
2022-12-28 20:03:29 +01:00
constructor(elt) {
2022-12-26 07:48:55 +01:00
this.items = [];
2022-12-28 20:03:29 +01:00
if (elt !== undefined) {
this.enqueue(elt, 0);
}
2022-12-26 07:48:55 +01:00
}
enqueue(element, priority) {
2022-12-28 20:03:29 +01:00
let qElement = new QElement(element, priority);
2022-12-26 07:48:55 +01:00
2022-12-28 20:03:29 +01:00
for (let i = 0; i < this.items.length; ++i) {
2022-12-26 07:48:55 +01:00
if (this.items[i].priority > qElement.priority) {
this.items.splice(i, 0, qElement);
2022-12-28 20:03:29 +01:00
return;
2022-12-26 07:48:55 +01:00
}
}
2022-12-28 20:03:29 +01:00
this.items.push(qElement);
2022-12-26 07:48:55 +01:00
}
dequeue() {
2022-12-28 20:03:29 +01:00
return this.items.shift(); // pop highest priority, use shift() for lower priority
2022-12-26 07:48:55 +01:00
}
front() {
return this.items[0];
}
rear() {
return this.items[this.items.length - 1];
}
isEmpty() {
2022-12-28 20:03:29 +01:00
return this.items.length === 0;
2022-12-26 07:48:55 +01:00
}
}