New:Microsoft Teams Notifications Are Now Available in Socket.Learn more →
Get Started

data-structure-typed

Package Overview
Dependencies
Maintainers
1
Versions
254
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

data-structure-typed

Standard data structure

Source
npmnpm
Version
2.5.0
Version published
Weekly downloads
22K
-28.3%
Maintainers
1
Weekly downloads
 
Created
Source

data-structure-typed

English | 简体中文

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

We TypeScript/JavaScript devs want something like C++'s STL, Java's java.util Collections, or Python's collections — but with an API that feels as intuitive and ergonomic as JavaScript's native Array. If that's what you're looking for, you're in the right place. This is a zero-dependency library, and you can also install individual data structure packages separately if you prefer a more modular setup.

npm GitHub contributors GITHUB Star codecov eslint NPM npm

📦 Installation • 🎮 Playground • ⚡ Quick Start • 📖 Docs • 📋 API • 💡 Examples

Table of Contents

📦 Installation

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

Individual Packages

Use only what you need:

npm i heap-typed deque-typed red-black-tree-typed

🎮 Playground

Try it instantly:

🎯 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 CaseArrayMapdata-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)

  • Optimized for V8 hot paths (see PERFORMANCE.md for measured benchmarks)

    • Repeated Array.shift() O(n) → Deque O(1)
    • Frequent update + keep-sorted workflows → RedBlackTree O(log n) operations
    • Avoid repeated Array.sort() if you must maintain sorted order after each update
  • Optimized for V8 JIT (Node.js 18+, modern browsers)

  • Tree-shakable ESM / CJS / legacy builds

Data StructureTest CaseDST (ms)Native (ms)C++ (ms)js-sdsl (ms)
Queue1M push26.9323.831.7027.59
Deque1M push9.7726.811.767.79
DoublyLinkedList100k push5.702.405.701.90
SinglyLinkedList100K unshift & shift3.771958.394.80-
PriorityQueue100K add4.00-1.054.96
TreeSet1M add995.72-462.00677.58
TreeMap1M set978.72-512.00623.23
TreeMultiSet1M add (TreeMultiSet expanded iteration)217.73-752.00-
TreeMultiMap1M add (TreeMultiMap bucketed)366.19-731.00-
RedBlackTree1M get99.24-52.97-
BST10K add randomly5.50---
BinaryTree1K add randomly9.77---
HashMap1M set146.17144.8376.2694.16
Trie100K add141.10---
DirectedGraph1K addVertex0.05---
Stack1M push46.3830.281.6532.38

📊 Full benchmarks → | Interactive report →

✨ 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

💡 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

StructureUse CaseTime ComplexityNPM
RedBlackTreeSorted collections, range queriesO(log n)npm
Heap / PriorityQueueTask scheduling, top-K elementsO(log n)npm
DequeFast front/back operationsO(1)npm
TrieAutocomplete, prefix searchO(m+k)npm
DirectedGraphPathfinding, DAG algorithmsO(V+E)npm
StackUndo/redo, expression parsingO(1)npm
LinkedListDynamic sizing, no index shiftO(1)*npm
AVLTreeStricter balance than RB-TreeO(log n)npm
SkipListSorted KV, TreeMap alternativeO(log n) avg—
SegmentTreeRange sum/min/max/custom queriesO(log n)—
BinaryIndexedTreePrefix sums, frequency countingO(log n)—
Matrix2D grid arithmeticO(n²) add—

👉 See all 20+ structures →

📖 Documentation

For Different Use Cases

Your GoalStart HereNext Steps
Learn conceptsCONCEPTS.mdGUIDES.md
Use in my projectGUIDES.mdREFERENCE.md
Look up APIREFERENCE.mdPERFORMANCE.md
Performance questionsPERFORMANCE.mdARCHITECTURE.md
Framework integrationINTEGRATIONS.mdGUIDES.md
Understand designARCHITECTURE.mdCONCEPTS.md

Documentation Files

  • Big Three Concepts (BST, Balanced Trees, Heap)
  • 13 Plain Language Explanations
  • Iterator Protocol Design
  • 5 Comparisons with Native JavaScript
  • Complete Decision Guide
  • Quick Reference Table
  • All 20+ Structures with Examples
  • CRUD Operations
  • Common Methods
  • TypeScript Support
  • Design Philosophy & Principles
  • 3 Pain Points Solved
  • Why Deque is 484x Faster
  • Iterator Protocol Design
  • Self-Balancing Strategy
  • V8 JIT Optimizations
  • Performance Summary
  • 3 Real-World Scenarios
  • Detailed Benchmarks
  • When to Use What
  • Optimization Tips
  • 4 Design Patterns
  • 5 Production Code Examples
  • Common Mistakes
  • Best Practices
  • 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 PointSolution
Repeated sorting slowing down codeTreeSet auto-maintains order
Array.shift timeout in loopsDeque O(1) shift instead of O(n)
Learning different APIsAll structures use push/pop/shift/unshift
Type safety nightmaresFull TypeScript generics support
Browser compatibility issuesWorks 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!

📊 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

Need range queries on array (sum/min/max)?
  → SegmentTree (any merge op) or BinaryIndexedTree (prefix sums only)

Need sorted key-value with same API as TreeMap?
  → SkipList (O(log n) avg, probabilistic balancing)

Otherwise?
  → Use Array (simplest case)

🤝 Contributing

Found a bug? Have suggestions? Open an issue

📄 License

MIT

📚 Full Documentation Structure

README.md (this file)
docs/
├── 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 →

Keywords

data structures typescript

FAQs

Package last updated on 27 Mar 2026

Related posts