Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Clearing the elements of the PriorityQueue using Javascript
In JavaScript, clearing a PriorityQueue can be accomplished by resetting the container array that holds the queue elements. This is a simple but effective approach.
Clear Method Implementation
The most straightforward way to clear a PriorityQueue is to reassign the container to an empty array:
clear() {
this.container = [];
}
Complete Example
Here's a working example demonstrating the clear functionality with a basic PriorityQueue implementation:
class PriorityQueue {
constructor() {
this.container = [];
}
enqueue(data, priority) {
this.container.push({data, priority});
this.container.sort((a, b) => a.priority - b.priority);
}
clear() {
this.container = [];
}
display() {
console.log(this.container);
}
}
let q = new PriorityQueue();
q.enqueue("Hello", 3);
q.enqueue("World", 2);
q.enqueue("Foo", 8);
console.log("Before clearing:");
q.display();
q.clear();
console.log("After clearing:");
q.display();
Before clearing:
[ { data: 'World', priority: 2 },
{ data: 'Hello', priority: 3 },
{ data: 'Foo', priority: 8 } ]
After clearing:
[ ]
How It Works
The clear method works by:
- Reassigning the
containerproperty to a new empty array - This removes all references to existing elements
- JavaScript's garbage collector will handle memory cleanup
- The queue is now ready to accept new elements
Alternative Approaches
You can also clear the array using other methods:
// Method 1: Reassignment (recommended)
clear() {
this.container = [];
}
// Method 2: Setting length to 0
clear() {
this.container.length = 0;
}
// Method 3: Using splice
clear() {
this.container.splice(0, this.container.length);
}
console.log("All methods achieve the same result");
All methods achieve the same result
Conclusion
Clearing a PriorityQueue is straightforward - simply reset the container array to empty. The reassignment approach is the most readable and commonly used method for this operation.
Advertisements
