官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 临海市| 黔西县| 黄山市| 普洱| 天祝| 延长县| 商南县| 金阳县| 商河县| 武宁县| 安吉县| 卢湾区| 赤峰市| 乐平市| 正蓝旗| 新龙县| 金湖县| 泸定县| 阜城县| 宣汉县| 房产| 沿河| 满洲里市| 卢氏县| 金沙县| 平安县| 营口市| 安丘市| 邳州市| 三明市| 屯昌县| 习水县| 衡南县| 蕉岭县| 咸宁市| 津市市| 高唐县| 新安县| 浦江县| 滦南县| 碌曲县|