From bf9cae236153d418f513e1d1997b4f68e9ec23c7 Mon Sep 17 00:00:00 2001 From: b-yogesh Date: Tue, 20 Oct 2020 11:52:44 +0200 Subject: [PATCH 1/2] added priority queue javascriptimplementation --- JavaScript/PriorityQueue/PriorityQueue.js | 88 +++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 JavaScript/PriorityQueue/PriorityQueue.js diff --git a/JavaScript/PriorityQueue/PriorityQueue.js b/JavaScript/PriorityQueue/PriorityQueue.js new file mode 100644 index 00000000..20cbbde7 --- /dev/null +++ b/JavaScript/PriorityQueue/PriorityQueue.js @@ -0,0 +1,88 @@ +class QElement { + constructor(priority, element) + { + this.priority = priority; + this.element = element; + } +} + +class PriorityQueue { + constructor() + { + this.items = []; + } + + enqueue(priority, element) + { + var qElement = new QElement(priority, element); + var contain = false; + + for (var i = 0; i < this.items.length; i++) { + if (this.items[i].priority >= qElement.priority) { + this.items.splice(i, 0, qElement); + contain = true; + break; + } + } + + if (!contain) { + this.items.push(qElement); + } + } + + + dequeue() + { + if (this.isEmpty()) + return "Underflow"; + return this.items.shift(); + } + + + front() + { + if (this.isEmpty()) + return "No elements in Queue"; + return this.items[0]; + } + + rear() + { + if (this.isEmpty()) + return "No elements in 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; + } + + includes(element){ + var isIncluded = false; + for (var i = 0; i < this.items.length; i++) + if(String(this.items[i].element) === String(element)) isIncluded = true; + return isIncluded; + } +} + + +var pq = new PriorityQueue(); + + +pq.enqueue(1, 4); +pq.enqueue(2, 7); + +console.log('frone ius', pq.front()); + +console.log(pq.rear()); + +console.log(pq.printPQueue()); \ No newline at end of file From d2578b093884cda3b19ac590f1f9a860841f0551 Mon Sep 17 00:00:00 2001 From: b-yogesh Date: Tue, 20 Oct 2020 11:54:34 +0200 Subject: [PATCH 2/2] updated --- JavaScript/PriorityQueue/PriorityQueue.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/JavaScript/PriorityQueue/PriorityQueue.js b/JavaScript/PriorityQueue/PriorityQueue.js index 20cbbde7..2c6fb622 100644 --- a/JavaScript/PriorityQueue/PriorityQueue.js +++ b/JavaScript/PriorityQueue/PriorityQueue.js @@ -81,8 +81,8 @@ var pq = new PriorityQueue(); pq.enqueue(1, 4); pq.enqueue(2, 7); -console.log('frone ius', pq.front()); +console.log(pq.front()); console.log(pq.rear()); -console.log(pq.printPQueue()); \ No newline at end of file +console.log(pq.printPQueue());