What is tinyqueue?
The tinyqueue npm package is a minimal priority queue implementation in JavaScript. It is designed to be very lightweight and fast, and it is often used for tasks that require a priority queue, such as pathfinding algorithms, scheduling, and event handling.
What are tinyqueue's main functionalities?
Creating a priority queue
This code sample demonstrates how to import the TinyQueue class and create a new priority queue instance.
const TinyQueue = require('tinyqueue');
const queue = new TinyQueue();
Adding items to the queue
This code sample shows how to add items to the queue with a specified priority. The lower the priority number, the sooner the item will be dequeued.
queue.push({ value: 'item1', priority: 1 });
queue.push({ value: 'item2', priority: 2 });
Removing the item with the highest priority
This code sample demonstrates how to remove and return the item with the highest priority (the item with the lowest priority number) from the queue.
const highestPriorityItem = queue.pop();
Peeking at the item with the highest priority without removing it
This code sample shows how to look at the item with the highest priority without removing it from the queue.
const highestPriorityItem = queue.peek();
Checking the size of the queue
This code sample demonstrates how to check the number of items in the queue.
const size = queue.length;
Other packages similar to tinyqueue
priorityqueuejs
PriorityQueue.js is another npm package that provides a priority queue implementation. It offers similar functionality to tinyqueue but has a different API and may have different performance characteristics.
js-priority-queue
js-priority-queue is a priority queue library for JavaScript that supports customizable ordering and initial queue contents. It is more feature-rich than tinyqueue, allowing for different strategies for storing the data and more complex comparison functions.
heap
The heap npm package is a binary heap implementation that can be used as a priority queue. It is more complex than tinyqueue and includes additional methods for heap operations, which might be useful for certain applications that require more control over the data structure.
tinyqueue
The smallest and simplest binary heap priority queue in JavaScript.
var queue = new TinyQueue();
queue.push(7);
queue.push(5);
queue.push(10);
var top = queue.pop();
top = queue.peek();
queue.length;
queue = new TinyQueue([7, 5, 10]);
queue = new TinyQueue([{value: 5}, {value: 7}], function (a, b) {
return a.value - b.value;
});
var array = [];
while (queue.length) array.push(queue.pop());
For a faster number-based queue, see flatqueue.
Install
Install using NPM (npm install tinyqueue
) or Yarn (yarn add tinyqueue
), then:
import TinyQueue from 'tinyqueue';
const TinyQueue = require('tinyqueue');
Or use a browser build directly:
<script src="https://unpkg.com/tinyqueue@2.0.0/tinyqueue.min.js"></script>
Thanks
Inspired by js-priority-queue
by Adam Hooper.