From db8369efaf40f4760c3470788bdc14d2b6266c22 Mon Sep 17 00:00:00 2001 From: Manish Date: Sun, 17 Sep 2023 18:52:24 +1000 Subject: [PATCH] Data Structures: Create a Priority Queue Class --- Data Structures/priorityQueueClass.js | 74 +++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Data Structures/priorityQueueClass.js diff --git a/Data Structures/priorityQueueClass.js b/Data Structures/priorityQueueClass.js new file mode 100644 index 0000000..6370ae4 --- /dev/null +++ b/Data Structures/priorityQueueClass.js @@ -0,0 +1,74 @@ +// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/create-a-priority-queue-class + +function PriorityQueue() { + this.collection = []; + this.printCollection = function () { + console.log( + this.collection.map(([elem, priority, order]) => [elem, priority]) + ); + }; + // Only change code below this line + this.order = 0; + this.size = function () { + return this.collection.length; + }; + this.isEmpty = function () { + return !this.collection.length; + }; + this.swap = function (a, b) { + const tmp = this.collection[a]; + this.collection[a] = this.collection[b]; + this.collection[b] = tmp; + }; + this.changePriority = function (a, b) { + return ( + this.collection[a][1] > this.collection[b][1] || + (this.collection[a][1] == this.collection[b][1] && + this.collection[a][2] > this.collection[b][2]) + ); + }; + this.enqueue = function (elem) { + elem.push(this.order++); + this.collection.push(elem); + let me = this.collection.length - 1; + let parent = Math.trunc((me - 1) / 2); + while (this.changePriority(parent, me)) { + this.swap(parent, me); + me = parent; + parent = Math.trunc((me - 1) / 2); + } + }; + this.dequeue = function () { + if (this.isEmpty()) return; + this.swap(0, this.collection.length - 1); + const elem = this.collection.pop()[0]; + let me = 0; + let leftChild = me * 2 + 1; + let rightChild = leftChild + 1; + while ( + (leftChild < this.collection.length && + this.changePriority(me, leftChild)) || + (rightChild < this.collection.length && + this.changePriority(me, rightChild)) + ) { + if ( + rightChild < this.collection.length && + this.changePriority(leftChild, rightChild) + ) { + this.swap(me, rightChild); + me = rightChild; + } else { + this.swap(me, leftChild); + me = leftChild; + } + leftChild = me * 2 + 1; + rightChild = leftChild + 1; + } + return elem; + }; + this.front = function () { + if (this.isEmpty()) return; + return this.collection[0][0]; + }; + // Only change code above this line +}