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

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.

主站蜘蛛池模板: 望都县| 临夏市| 原阳县| 通海县| 漯河市| 星子县| 鹤岗市| 岳普湖县| 志丹县| 菏泽市| 康平县| 宁蒗| 高唐县| 法库县| 都江堰市| 石家庄市| 含山县| 松潘县| 崇礼县| 内丘县| 扶余县| 固安县| 嘉鱼县| 海淀区| 佛教| 无锡市| 根河市| 眉山市| 梅州市| 钟祥市| 汪清县| 北宁市| 扶风县| 开远市| 全椒县| 高清| 新丰县| 林口县| 澄城县| 都江堰市| 汤阴县|