FlatQueue

3.0.0 · active · verified Sun Apr 19

flatqueue is a highly optimized JavaScript priority queue implementation that leverages a binary heap structure, distinguished by storing items and their numeric priorities in two separate, flat arrays. This design choice, while limiting custom comparator functions, enables significant performance gains, often several times faster than alternatives like tinyqueue. The package is currently at version 3.0.0, primarily focused on modern JavaScript environments, being ESM-only since version 2.0.0, with further streamlining in v3.0.0 by dropping the legacy UMD bundle. It ships with first-class TypeScript types via JSDoc. Its core differentiators include its minimalistic API, small footprint, and exceptional speed, particularly effective in scenarios requiring frequent push and pop operations, making it suitable for algorithms like A* pathfinding or event schedulers where performance is critical. Its release cadence indicates active maintenance, with recent versions focusing on performance optimizations and module system compatibility, ensuring it remains a performant choice for priority queue needs in web and Node.js applications.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to create a FlatQueue, push items with associated priorities, peek at the top item, pop the lowest-priority item, and clear the queue. It highlights basic API usage and the queue's length property.

import FlatQueue from 'flatqueue';

interface Item {
  id: number;
  priority: number;
  data: string;
}

const q = new FlatQueue();

const items: Item[] = [
  { id: 0, priority: 5, data: 'task A' },
  { id: 1, priority: 1, data: 'task B' },
  { id: 2, priority: 8, data: 'task C' },
  { id: 3, priority: 2, data: 'task D' }
];

console.log('Pushing items...');
for (let i = 0; i < items.length; i++) {
  // Push the item's original ID (or the item itself) and its priority value.
  // Storing only integers (like IDs/indices) is generally faster for JavaScript engine optimizations.
  q.push(items[i].id, items[i].priority);
}

console.log(`\nQueue length: ${q.length}`);
console.log(`Top item (ID): ${q.peek()}`); // Expected: 1 (ID of task B)
console.log(`Top item priority: ${q.peekValue()}`); // Expected: 1

const poppedId = q.pop(); // Removes ID 1
console.log(`Popped item ID: ${poppedId}`); // Expected: 1

console.log(`\nNew top item (ID): ${q.peek()}`); // Expected: 3 (ID of task D)
console.log(`New top item priority: ${q.peekValue()}`); // Expected: 2

q.clear();
console.log(`\nQueue length after clear: ${q.length}`); // Expected: 0

view raw JSON →