Skip to content

agnat/js_priority_queue

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

25 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Priority Queue

A simple javascript priority queue using a binary heap. A compare function is used to sort the elements. The queue works in CommonJS and browser environments.

Synopsis

var pq = require('priority_queue');

// create a queue
var q = new pq.PriorityQueue();

// push some elements
q.push(42, 5, 23, Math.PI);

// shift 'em out ...
while (q.length > 0) {
  console.log(q.shift());
}

Installation

npm install priority_queue

To use the queue in a web page add

<script src='/scripts/priority_queue.js' type='text/javascript'></script>

The module is exported as agnat_priority_queue.

Documentation

pq.PriorityQueue(compare, queue)

Construct a new priority queue. compare is a function with the same semantics as the compare functions used with Array.sort(). It defaults to a simple numeric comparison with ascending order.

An initial queue array may be passed in using the queue argument. Note that the content of the array will be modified.

The constructor may be called with or without operator new.

queue.push(element, …)

Add new elements to the queue. Returns the new length.

queue.shift()

Remove the item with maximum priority from the queue and return it.

queue.length

The current length of the queue.

Compare Functions

Two compare functions are included. They are not very useful because they only compare numbers. However, they are used in testing and provide a starting point to implement your own.

pq.min_first

Return items with minimum priority first

pq.max_first

Return items with maximum priority first

License

MIT.

About

A simple javascript priority queue using a binary heap

Resources

License

Stars

Watchers

Forks

Packages

No packages published