Created
December 30, 2022 16:44
-
-
Save mcmoe/66716ffdae2816a743e5a431ecdbb8bf to your computer and use it in GitHub Desktop.
Simple array-based priority queue in JavaScript with change priority capability
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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