class QueueElement {
constructor(element, priority) {
this.element = element;
this.priority = priority;
}
}
class PriorityQueue {
constructor() {
this.queueItems = [];
}
enqueueFunction(element, priority) {
let queueElement = new QueueElement(element, priority);
let contain = false;
for (let i = 0; i < this.queueItems.length; i++) {
if (this.queueItems[i].priority > queueElement.priority) {
this.queueItems.splice(i, 0, queueElement);
contain = true;
break;
}
}
/* if the input element has the highest priority push it to end of the queue */
if (!contain) {
this.queueItems.push(queueElement);
}
}
dequeueFunction() {
/* returns the removed element from priority queue. */
if (this.isPriorityQueueEmpty()) {
return "No elements present in Queue";
}
return this.queueItems.shift();
}
front() {
/* returns the highest priority queue element without removing it. */
if (this.isPriorityQueueEmpty()) {
return "No elements present in Queue";
}
return this.queueItems[0];
}
rear() {
/* returns the lowest priority queue element without removing it. */
if (this.isPriorityQueueEmpty()) {
return "No elements present in Queue";
}
return this.queueItems[this.queueItems.length - 1];
}
isPriorityQueueEmpty() {
/* Checks the length of an queue */
return this.queueItems.length === 0;
}
/* prints all the elements of the priority queue */
printPriorityQueue() {
let queueString = "";
for (let i = 0; i < this.queueItems.length; i++)
queueString += this.queueItems[i].element + " ";
return queueString;
}
}
let priorityQueue = new PriorityQueue();
console.log(priorityQueue.isPriorityQueueEmpty());
console.log(priorityQueue.front());
priorityQueue.enqueueFunction("Sonya", 2);
priorityQueue.enqueueFunction("John", 1);
priorityQueue.enqueueFunction("Alma", 1);
priorityQueue.enqueueFunction("Alexander", 2);
priorityQueue.enqueueFunction("Arthur", 3);
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.