- Hands-On Data Structures and Algorithms with JavaScript
- Kashyap Mukkamala
- 325字
- 2021-06-30 19:12:13
Testing a priority queue
Let's first set up the data for testing the queue:
var priorityQueue = new PriorityQueue();
priorityQueue.add({ el : 1, priority: 1});
// state of Queue
// [1]
// ^
priorityQueue.add({ el : 2, priority: 2});
// state of Queue
// [2, 1]
// ^
priorityQueue.add({ el : 3, priority: 3});
// state of Queue
// [3, 2, 1]
// ^
priorityQueue.add({ el : 4, priority: 3});
// state of Queue
// [3, 4, 2, 1]
// ^
priorityQueue.add({ el : 5, priority: 2});
// state of Queue
// [3, 4, 2, 5, 1]
// ^
Visually, the preceding steps would generate a queue that looks like the following:

From the preceding figure, we can note how when we add an element with a priority 2 it gets placed ahead of all the elements with priority 1:
priorityQueue.add({ el : 6, priority: 1});
// state of Queue
// [3, 4, 2, 5, 1, 6]
// ^
And when we add an element with priority 1 (lowest) it gets added to the end of the queue:

The last element that we add here happens to be the one with the lowest priority as well, which makes it the last element of the queue, thus keeping all the elements ordered based on priority.
Now, let's remove elements from the queue:
console.log(priorityQueue.remove());
// prints { el: 3, priority: 3}
// state of Queue
// [4, 2, 5, 1, 6]
console.log(priorityQueue.remove());
// prints { el: 4, priority: 3 }
// state of Queue
// [2, 5, 1, 6]
console.log(priorityQueue.remove());
// prints { el: 2, priority: 2 }
// state of Queue
// [5, 1, 6]
priorityQueue.print();
// prints { el: 5, priority: 2 } { el: 1, priority: 1 } { el: 6, priority: 1 }
There we have it: the creation of simple and priority queues in JavaScript using WeakMap(). Let's now take a look at some of the practical applications of these queues.
- 數(shù)據(jù)庫系統(tǒng)原理及MySQL應用教程(第2版)
- OpenDaylight Cookbook
- Python入門很簡單
- 軟件界面交互設計基礎
- Game Programming Using Qt Beginner's Guide
- MySQL 8 DBA基礎教程
- Instant 960 Grid System
- 深度強化學習算法與實踐:基于PyTorch的實現(xiàn)
- Mastering Drupal 8 Views
- Django 3.0入門與實踐
- Beginning C++ Game Programming
- JavaScript機器人編程指南
- 微信小程序開發(fā)實戰(zhàn):設計·運營·變現(xiàn)(圖解案例版)
- 深入大型數(shù)據(jù)集:并行與分布化Python代碼
- Android開發(fā)權威指南(第二版)