npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@js-structure/heap

v1.0.2

Published

expand heap data structure for javascript

Downloads

106

Readme

@js-structure/heap

A high-performance heap data structure implementation for JavaScript/TypeScript, supporting both min-heap and max-heap.

Features

  • 🚀 Generic support with full type safety
  • 📦 Both min-heap and max-heap support
  • 🔧 Custom comparator functions
  • ⚡ High-performance heap operations
  • 🔄 Iterator protocol support (for...of, spread operator)
  • 🎯 Method chaining
  • ✅ Comprehensive test coverage
  • 📝 TypeScript type definitions

Installation

npm install @js-structure/heap

Quick Start

Min Heap

import Heap from '@js-structure/heap';

const minHeap = new Heap<number>(Heap.MIN_HEAP);

minHeap.push(5).push(3).push(7).push(1);

console.log(minHeap.top()); // 1
console.log(minHeap.pop()); // 1
console.log(minHeap.pop()); // 3

Max Heap

const maxHeap = new Heap<number>(Heap.MAX_HEAP);

maxHeap.push(5).push(3).push(7).push(1);

console.log(maxHeap.top()); // 7
console.log(maxHeap.pop()); // 7

Create Heap with Initial Values

const heap = new Heap<number>(Heap.MIN_HEAP, [5, 3, 7, 1, 9, 2]);
heap.balance(); // Balance the heap

console.log(heap.top()); // 1

Custom Comparator

interface Task {
  name: string;
  priority: number;
}

const taskHeap = new Heap<Task>(
  (a, b) => a.priority < b.priority,
  [
    { name: 'task1', priority: 5 },
    { name: 'task2', priority: 1 },
    { name: 'task3', priority: 3 }
  ]
);

taskHeap.balance();
console.log(taskHeap.top()); // { name: 'task2', priority: 1 }

API

Constructor

constructor(comparator: (a: T, b: T) => boolean, value?: T[])

Creates a new heap instance.

  • comparator: Comparison function, returns true if first argument should be closer to the top
  • value: Optional initial values array

Static Properties

  • Heap.MIN_HEAP - Built-in min-heap comparator
  • Heap.MAX_HEAP - Built-in max-heap comparator

Methods

push(value: T): Heap<T>

Adds an element to the heap and maintains heap property.

heap.push(5).push(3).push(7);

pop(): T | null

Removes and returns the top element. Returns null if heap is empty.

const value = heap.pop();

top(): T | null

Returns the top element without removing it. Returns null if heap is empty.

const value = heap.top();

isEmpty(): boolean

Checks if the heap is empty.

size(): number

Returns the number of elements in the heap.

clear(): Heap<T>

Removes all elements from the heap.

clone(): Heap<T>

Creates a copy of the heap.

isValid(): boolean

Checks if the heap satisfies the heap property.

balance(): Heap<T>

Balances the heap. Call this method after creating a heap from an array.

const heap = new Heap(Heap.MIN_HEAP, [5, 3, 7, 1]);
heap.balance();

toArray(): T[]

Returns an array representation of the heap.

Iterator Support

The heap implements the iterator protocol and can be used with for...of loops and spread operators.

Note: Iteration consumes the heap elements (calls pop()), leaving the heap empty.

const heap = new Heap(Heap.MIN_HEAP, [5, 3, 7, 1, 9]);
heap.balance();

for (const value of heap) {
  console.log(value); // Output in order: 1, 3, 5, 7, 9
}

// Using spread operator
const heap2 = new Heap(Heap.MAX_HEAP, [5, 3, 7, 1]);
heap2.balance();
const sorted = [...heap2]; // [7, 5, 3, 1]

Use Cases

Priority Queue

interface Job {
  id: string;
  priority: number;
  task: () => void;
}

const jobQueue = new Heap<Job>(
  (a, b) => a.priority > b.priority
);

jobQueue.push({ id: '1', priority: 5, task: () => console.log('Job 1') });
jobQueue.push({ id: '2', priority: 10, task: () => console.log('Job 2') });

while (!jobQueue.isEmpty()) {
  const job = jobQueue.pop();
  job?.task();
}

Top K Elements

function topK(arr: number[], k: number): number[] {
  const minHeap = new Heap<number>(Heap.MIN_HEAP);
  
  for (const num of arr) {
    if (minHeap.size() < k) {
      minHeap.push(num);
    } else if (minHeap.top()! < num) {
      minHeap.pop();
      minHeap.push(num);
    }
  }
  
  return minHeap.toArray();
}

console.log(topK([3, 1, 5, 9, 2, 7, 4, 8, 6], 3)); // [7, 8, 9]

Heap Sort

function heapSort(arr: number[]): number[] {
  const heap = new Heap<number>(Heap.MIN_HEAP, arr);
  heap.balance();
  
  return [...heap]; // Uses iterator
}

console.log(heapSort([5, 3, 7, 1, 9, 2])); // [1, 2, 3, 5, 7, 9]

Complexity

| Operation | Time Complexity | |-----------|----------------| | push() | O(log n) | | pop() | O(log n) | | top() | O(1) | | isEmpty() | O(1) | | size() | O(1) | | balance() | O(n) | | clone() | O(n) | | toArray() | O(n) | | isValid() | O(n) |

Space Complexity: O(n)