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.