Skip to content

Javascript Data Structure & TypeScript Data Structure. Heap, Binary Tree, Red Black Tree, Linked List, Deque, Trie, HashMap, Directed Graph, Undirected Graph, Binary Search Tree, AVL Tree, Priority Queue, Graph, Queue, Tree Multiset, Singly Linked List, Doubly Linked List, Max Heap, Max Priority Queue, Min Heap, Min Priority Queue, Stack.

License

Notifications You must be signed in to change notification settings

zrwusa/data-structure-typed

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

README: data-structure-typed Library

A comprehensive TypeScript data structures library with production-ready implementations.

๐Ÿ“š Installation โ€ข Quick Start โ€ข Full Docs โ€ข API Reference โ€ข Playground โ€ข Examples


Table of Contents

  1. Who Should Use This?
  2. Why Not Just Array or Map?
  3. Key Features
  4. Installation
  5. Quick Start
  6. Data Structures
  7. Documentation

๐ŸŽฏ Who Should Use This?

If you are building ranked collections, scheduling queues, or sorted data structures in TypeScript,
consider data-structure-typed instead of hand-rolled Arrays or Maps.

Perfect for:

  • Leaderboards & Rankings โ€” Maintain top-K efficiently without repeated sorting
  • Task Scheduling โ€” Priority queues, ordered execution, time-based operations
  • Real-Time Dashboards โ€” Grafana-style workloads with instant lookups
  • Time-Series Data โ€” Sorted insertion + fast range queries
  • Search & Autocomplete โ€” Prefix matching at scale
  • Graph Problems โ€” Pathfinding, cycle detection, topological sorting

โšก Why Not Just Array or Map?

Use Case Array Map data-structure-typed
Sorted Lookup โŒ O(n) โŒ Unordered โœ… O(log n)
Insert at Position โŒ O(n) shift โŒ No position โœ… O(log n)
Leaderboard Top-K โŒ Re-sort O(n log n) โŒ Manual sort โœ… Instant
Remove from Front โŒ O(n) โŒ No dequeue โœ… O(1)
Prefix Search โŒ O(n*m) โŒ Not applicable โœ… O(m + k)
Familiar API โœ… Yes โœ… Yes โœ… Same

Real-World Pain Point

// โŒ WITHOUT data-structure-typed
const queue = [1, 2, 3, ..., 100000
]
;
for (let i = 0; i < 100000; i++) {
  queue.shift();  // O(n) - Reindexes EVERY element!
}
// Time: 2829ms โŒ
// โœ… WITH data-structure-typed (Deque)
const deque = new Deque([1, 2, 3, ..., 100000])
;
for (let i = 0; i < 100000; i++) {
  deque.shift();  // O(1) - Just moves a pointer
}
// Time: 5.83ms โœ…
// **484x faster!**

๐Ÿš€ Performance (TL;DR)

  • 10โ€“40% faster than common JS implementations in hot paths

    • Array.sort() O(n log n) โ†’ TreeSet O(log n) insertion
    • Repeated Array.shift() O(n) โ†’ Queue O(1)
    • Manual index tracking โ†’ RB-Tree auto-balance
  • Optimized for V8 JIT (Node.js 18+, modern browsers)

  • Tree-shakable ESM / CJS / legacy builds

๐Ÿ“Š Full benchmarks โ†’


โœจ Key Features

๐Ÿ  Uniform API

Don't learn new APIs. Just use push, pop, map, filter, and reduce everywhere.

// All linear structures use THE SAME 4 methods
const deque = new Deque([1, 2, 3]);
const queue = new Queue([1, 2, 3]);
const doublyLinkeList = new DoublyLinkedList([1, 2, 3]);
const singlyLinkedList = new SinglyLinkedList([1, 2, 3]);

// They ALL support:
structure.push(item);          // Add to end
structure.pop();               // Remove from end
structure.shift();             // Remove from start
structure.unshift(item);       // Add to start

๐Ÿ›ก๏ธ Type Safe

Full generics and strict TypeScript support out of the box.

const tree = new RedBlackTree<number, string>();
tree.set(1, 'Alice');
tree.set(2, 'Bob');

// Type-safe access
const value = tree.get(1);  // Type: string | undefined

โœจ Zero Friction

Works everywhere. Spread it [...], loop it for..of, convert it instantly.

// All data structures work with iterator protocol
const tree = new RedBlackTree([5, 2, 8]);
const sorted = [...tree];              // Spread operator
for (const item of tree) {
}           // for...of loop
const set = new Set(tree);             // Set constructor

๐Ÿ“ฅ Installation

pnpm add data-structure-typed
npm i data-structure-typed --save
yarn add data-structure-typed

Individual Packages

Use only what you need:

pnpm add heap-typed deque-typed red-black-tree-typed

๐Ÿ’ก When Should I Consider This Library?

โœ… When you need:

  • Top-K / Leaderboard queries without repeated sorting
  • Insertion order + lookup performance simultaneously
  • Priority queues with fast position-based access
  • Time-series data with range queries
  • Red-Black Tree / Heap performance without learning new APIs

โœ… When your current code has:

  • array.sort() in hot paths (request handlers, loops)
  • Manual index tracking after insertions
  • Array.shift() on large lists (queues)
  • Custom sorting logic you repeat across files
  • Map that needs to be ordered

๐Ÿš€ Quick Start: 30 Seconds

Leaderboard (Ranked Collections)

import { RedBlackTree } from 'data-structure-typed';

const leaderboard = new RedBlackTree([
  [100, 'Alice'],
  [85, 'Bob'],
  [92, 'Charlie']
]);

// Get sorted scores (automatically maintained!)
for (const [score, player] of leaderboard) {
  console.log(`${player}: ${score}`);
}
// Output:
// Alice: 100
// Charlie: 92
// Bob: 85

// Update score
leaderboard.delete(85);
leaderboard.set(95, 'Bob');  // O(log n)

// Query top players
const topPlayers = [...leaderboard.values()].reverse().slice(0, 3);

Task Queue (Scheduling)

import { MaxPriorityQueue } from 'data-structure-typed';

const taskQueue = new MaxPriorityQueue<{priority: number; task: string}>([], {
  comparator: (a, b) => b.priority - a.priority
});

taskQueue.add({ priority: 5, task: 'Email' });
taskQueue.add({ priority: 9, task: 'Alert' });  // Instant priority handling

const nextTask = taskQueue.poll();  // { priority: 9, task: 'Alert' }

Fast Queue (FIFO)

import { Deque } from 'data-structure-typed';

const queue = new Deque([1, 2, 3, 4, 5]);
queue.shift();  // Remove from front: O(1) not O(n)
queue.push(6);  // Add to back: O(1)

๐Ÿ“Š Data Structures Available

Structure Use Case Time Complexity NPM
RedBlackTree Sorted collections, range queries O(log n) npm
Heap / PriorityQueue Task scheduling, top-K elements O(log n) npm
Deque Fast front/back operations O(1) npm
Trie Autocomplete, prefix search O(m+k) npm
DirectedGraph Pathfinding, DAG algorithms O(V+E) npm
Stack Undo/redo, expression parsing O(1) npm
LinkedList Dynamic sizing, no index shift O(1)* npm
AVLTree Stricter balance than RB-Tree O(log n) npm

๐Ÿ‘‰ See all 20+ structures โ†’


๐Ÿ“– Documentation

For Different Use Cases

Your Goal Start Here Next Steps
Learn concepts CONCEPTS.md GUIDES.md
Use in my project GUIDES.md REFERENCE.md
Look up API REFERENCE.md PERFORMANCE.md
Performance questions PERFORMANCE.md ARCHITECTURE.md
Framework integration INTEGRATIONS.md GUIDES.md
Understand design ARCHITECTURE.md CONCEPTS.md

Documentation Files

  1. CONCEPTS.md - Core Fundamentals & Theory
  • Big Three Concepts (BST, Balanced Trees, Heap)
  • 13 Plain Language Explanations
  • Iterator Protocol Design
  • 5 Comparisons with Native JavaScript
  • Complete Decision Guide
  1. REFERENCE.md - Complete API & Data Structures
  • Quick Reference Table
  • All 20+ Structures with Examples
  • CRUD Operations
  • Common Methods
  • TypeScript Support
  1. ARCHITECTURE.md - Design & Implementation
  • Design Philosophy & Principles
  • 3 Pain Points Solved
  • Why Deque is 484x Faster
  • Iterator Protocol Design
  • Self-Balancing Strategy
  • V8 JIT Optimizations
  1. PERFORMANCE.md - Benchmarks & Comparisons
  • Performance Summary
  • 3 Real-World Scenarios
  • Detailed Benchmarks
  • When to Use What
  • Optimization Tips
  1. GUIDES.md - Real-World Examples
  • 4 Design Patterns
  • 5 Production Code Examples
  • Common Mistakes
  • Best Practices
  1. INTEGRATIONS.md - Framework Integration
  • React Integration (State Management, Leaderboard)
  • Express Integration (LRU Cache, Rate Limiting)
  • Nest.js Integration (Ranking Service, Task Queue)
  • TypeScript Configuration

๐Ÿ’ป Real-World Examples

LRU Cache

class LRUCache<K, V> {
  private cache = new Map<K, V>();
  private order = new DoublyLinkedList<K>();

  get(key: K): V | null {
    if (!this.cache.has(key)) return null;
    // Move to end (recently used)
    // Efficient with O(1) operations
    return this.cache.get(key)!;
  }
}

Leaderboard

type Player = {
  id: string;
  name: string;
  score: number;
};

const seedPlayers: Player[] = [
  { id: 'player_01HZX4E8Q2K8Y3J9M7T1A6B3C4', name: 'Pablo', score: 65 },
  { id: 'player_01HZX4E9R6V2D8K1P0N5S4T7U8', name: 'Bunny', score: 10 },
  { id: 'player_01HZX4EA3M9Q7W1E2R8T6Y5U0I', name: 'Jeff', score: 99 },
];

class ScoreLeaderboard {
  private readonly byScore: RedBlackTree<number, Player, Player>;

  constructor(initialPlayers: Player[]) {
    this.byScore = new RedBlackTree<number, Player, Player>(initialPlayers, {
      isMapMode: false,// Use "node value" storage rather than Map-style.
      toEntryFn: (player) => [player.score, player], // Convert a player object into the tree entry: key = score, value = player.
    });
  }

  /**
   * Returns players whose scores fall within the given range.
   * Supports either a tuple [min, max] or a Range object for inclusive/exclusive bounds.
   */
  public findPlayersByScoreRange(range: [number, number] | Range<number>): (Player | undefined)[] {
    return this.byScore.rangeSearch(range, (node) => node.value);
  }
  
  public upsertPlayer(player: Player) {
    return this.byScore.set(player.score, player);
  }
}

const leaderboard = new ScoreLeaderboard(seedPlayers);

console.log(leaderboard.findPlayersByScoreRange([65, 100]));

leaderboard.upsertPlayer({
  id: 'player_01HZX4EB7C4N2M9Q8R1T3Y6U5I',
  name: 'Alex',
  score: 80,
});

console.log(leaderboard.findPlayersByScoreRange(new Range(65, 100, true, true)));

Message Queue

type Message = {
  id: string;
  type: string;
  payload: unknown;
  priority: 'urgent' | 'normal';
  createdAt: number;
  retryCount?: number;
};

class MessageQueue {
  private urgent = new Deque<Message>();
  private normal = new Deque<Message>();

  dequeue(): Message | null {
    return this.urgent.shift() || this.normal.shift();
  }
}

๐Ÿ‘‰ More examples in GUIDES.md


๐ŸŽฏ Use Cases by Industry

๐Ÿ“Š Finance

  • Price-sorted order book
  • Real-time portfolio rankings
  • Option chain ordering

๐ŸŽฎ Gaming

  • Player leaderboards
  • Enemy priority queues
  • Game event scheduling

๐Ÿ“ฑ Social Media

  • Trending posts (top-K)
  • Feed ordering
  • Notification scheduling

๐Ÿฅ Healthcare

  • Patient priority queues
  • Appointment scheduling
  • Medical record organization

๐Ÿ›’ E-commerce

  • Product price ranges
  • Inventory management
  • Order scheduling

โœจ Why Developers Love This

Pain Point Solution
Repeated sorting slowing down code TreeSet auto-maintains order
Array.shift timeout in loops Deque O(1) shift instead of O(n)
Learning different APIs All structures use push/pop/shift/unshift
Type safety nightmares Full TypeScript generics support
Browser compatibility issues Works everywhere: Node, browsers, CDN

๐Ÿ“ฆ What You Get

โœ… 20+ data structures (production-ready)
โœ… 50+ code examples (real-world patterns)
โœ… Full TypeScript support (strict typing)
โœ… Performance benchmarks (484x speedups)
โœ… Framework integrations (React, Express, Nest.js) โœ… 6 core documentation files (2500+ lines)


๐Ÿš€ Getting Started

Step 1: Install

npm i data-structure-typed

Step 2: Import

import { RedBlackTree, Deque, MaxPriorityQueue } from 'data-structure-typed';

Step 3: Use

const tree = new RedBlackTree([5, 2, 8]);
console.log([...tree]);  // [2, 5, 8] - Automatically sorted!

Playground

๐Ÿƒ๐Ÿปโ€โ™€๏ธ Try it instantly:

Step 4: Learn More

๐Ÿ‘‰ Check CONCEPTS.md for core concepts
๐Ÿ‘‰ See GUIDES.md for production examples
๐Ÿ‘‰ Read REFERENCE.md for complete API


๐Ÿ“Š Comparison Chart

Need frequent head/tail operations?
  โ†’ Deque (O(1) shift/unshift/push/pop)

Need sorted + fast lookup?
  โ†’ RedBlackTree (O(log n) guaranteed)

Need highest/lowest priority?
  โ†’ Heap/PriorityQueue (O(log n) add/remove)

Need prefix/text matching?
  โ†’ Trie (O(m+k) where m=prefix)

Need graph operations?
  โ†’ DirectedGraph/UndirectedGraph

Otherwise?
  โ†’ Use Array (simplest case)

๐Ÿค Contributing

Found a bug? Have suggestions? Open an issue


๐Ÿ“„ License

MIT


๐Ÿ“š Full Documentation Structure

docs/
โ”œโ”€โ”€ README.md (this file)
โ”œโ”€โ”€ CONCEPTS.md (theory & fundamentals)
โ”œโ”€โ”€ REFERENCE.md (API documentation)
โ”œโ”€โ”€ ARCHITECTURE.md (design principles)
โ”œโ”€โ”€ PERFORMANCE.md (benchmarks)
โ”œโ”€โ”€ GUIDES.md (real-world examples)
โ””โ”€โ”€ INTEGRATIONS.md (framework guides)

๐ŸŽ“ Learn More

Just started? โ†’ Quick Start

Need concepts? โ†’ CONCEPTS.md

Want to build? โ†’ GUIDES.md

Need API? โ†’ REFERENCE.md

Curious about performance? โ†’ PERFORMANCE.md

Framework questions? โ†’ INTEGRATIONS.md


Ready to supercharge your TypeScript data structures? Get started now โ†’

About

Javascript Data Structure & TypeScript Data Structure. Heap, Binary Tree, Red Black Tree, Linked List, Deque, Trie, HashMap, Directed Graph, Undirected Graph, Binary Search Tree, AVL Tree, Priority Queue, Graph, Queue, Tree Multiset, Singly Linked List, Doubly Linked List, Max Heap, Max Priority Queue, Min Heap, Min Priority Queue, Stack.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

No packages published