- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
The PriorityQueue Class in Javascript
Here is the complete implementation of the PriorityQueue class −
Example
class PriorityQueue { constructor(maxSize) { // Set default max size if not provided if (isNaN(maxSize)) { maxSize = 10; } this.maxSize = maxSize; // Init an array that'll contain the queue values. this.container = []; } // Helper function to display all values while developing display() { console.log(this.container); } // Checks if queue is empty isEmpty() { return this.container.length === 0; } // checks if queue is full isFull() { return this.container.length >= this.maxSize; } enqueue(data, priority) { // Check if Queue is full if (this.isFull()) { console.log("Queue Overflow!"); return; } let currElem = new this.Element(data, priority); let addedFlag = false; // Since we want to add elements to end, we'll just push them. for (let i = 0; i < this.container.length; i++) { if (currElem.priority < this.container[i].priority) { this.container.splice(i, 0, currElem); addedFlag = true; break; } } if (!addedFlag) { this.container.push(currElem); } } dequeue() { // Check if empty if (this.isEmpty()) { console.log("Queue Underflow!"); return; } return this.container.pop(); } peek() { if (isEmpty()) { console.log("Queue Underflow!"); return; } return this.container[this.container.length - 1]; } clear() { this.container = []; } } // Create an inner class that we'll use to create new nodes in the queue // Each element has some data and a priority PriorityQueue.prototype.Element = class { constructor(data, priority) { this.data = data; this.priority = priority; } };
- Related Articles
- PriorityQueue Class in Java Programming
- Clearing the elements of the PriorityQueue using Javascript
- Add elements to a PriorityQueue using Javascript
- Remove elements from a PriorityQueue using Javascript
- Peeking elements from a PriorityQueue using JavaScript
- Implement PriorityQueue through Comparator in Java
- The Stack Class in Javascript
- The Queue Class in Javascript
- The Set Class in Javascript
- The Dictionary Class in Javascript
- The HashTable Class in Javascript
- The Linked List Class in Javascript
- Class Keyword in JavaScript
- The Doubly Linked List class in Javascript
- AVL Tree class in Javascript

Advertisements