Skip to content

Instantly share code, notes, and snippets.

@mcmoe
Created December 30, 2022 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcmoe/66716ffdae2816a743e5a431ecdbb8bf to your computer and use it in GitHub Desktop.
Save mcmoe/66716ffdae2816a743e5a431ecdbb8bf to your computer and use it in GitHub Desktop.
Simple array-based priority queue in JavaScript with change priority capability
// Priority Queue Item
class PQi {
constructor(item, priority) {
this.item = item;
this.priority = priority;
}
}
// Priority Queue
class PQ {
constructor() {
this.items = [];
}
enqueue(item, priority) {
const pqi = new PQi(item, priority);
let added = false;
for(let i = 0; i < this.items.length; ++i) {
if(priority < this.items[i].priority) {
this.items.splice(i, 0, pqi);
added = true;
break;
}
}
if(!added) { // then priority is highest, just add at end of array
this.items.push(pqi);
}
}
dequeue() {
return this.items.shift();
}
changePriority(item, newPriority) {
for(let i = 0; i < this.items.length; ++i) {
if(item === this.items[i].item) {
this.items.splice(i, 1);
break;
}
}
this.enqueue(item, newPriority);
}
isEmpty() {
return this.items.length === 0;
}
peekFirst() {
return this.items[0];
}
peekLast() {
return this.items[this.items.length-1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment