{"id":20113732,"url":"https://github.com/zrwusa/data-structure-typed","last_synced_at":"2026-04-02T16:32:34.258Z","repository":{"id":175631466,"uuid":"654220571","full_name":"zrwusa/data-structure-typed","owner":"zrwusa","description":"TypeScript \u0026 Javascript Data Structures","archived":false,"fork":false,"pushed_at":"2026-03-29T22:00:34.000Z","size":47270,"stargazers_count":195,"open_issues_count":2,"forks_count":11,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-03-29T22:22:50.069Z","etag":null,"topics":["avl-tree","binary-tree","data-structures","deque","graph","hash-map","heap","javascript","leetcode","linked-list","priority-queue","red-black-tree","segment-tree","skip-list","sorted-collections","tree-map","tree-set","trie","typescript","zero-dependencies"],"latest_commit_sha":null,"homepage":"https://data-structure-typed-docs.vercel.app","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zrwusa.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2023-06-15T16:32:49.000Z","updated_at":"2026-03-29T22:00:38.000Z","dependencies_parsed_at":null,"dependency_job_id":"de5e3144-23c0-4e1b-a0be-924ac5462326","html_url":"https://github.com/zrwusa/data-structure-typed","commit_stats":{"total_commits":554,"total_committers":7,"mean_commits":79.14285714285714,"dds":"0.023465703971119134","last_synced_commit":"691fb628935102a842aa4a26ea3d10fd36bab1e8"},"previous_names":["zrwusa/data-structure-typed"],"tags_count":15,"template":false,"template_full_name":null,"purl":"pkg:github/zrwusa/data-structure-typed","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zrwusa%2Fdata-structure-typed","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zrwusa%2Fdata-structure-typed/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zrwusa%2Fdata-structure-typed/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zrwusa%2Fdata-structure-typed/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zrwusa","download_url":"https://codeload.github.com/zrwusa/data-structure-typed/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zrwusa%2Fdata-structure-typed/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31310063,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-02T12:59:32.332Z","status":"ssl_error","status_checked_at":"2026-04-02T12:54:48.875Z","response_time":89,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["avl-tree","binary-tree","data-structures","deque","graph","hash-map","heap","javascript","leetcode","linked-list","priority-queue","red-black-tree","segment-tree","skip-list","sorted-collections","tree-map","tree-set","trie","typescript","zero-dependencies"],"created_at":"2024-11-13T18:25:35.309Z","updated_at":"2026-04-02T16:32:34.241Z","avatar_url":"https://github.com/zrwusa.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"# data-structure-typed\n\nEnglish | [简体中文](./README_CN.md)\n\nA production-ready TypeScript data structures library featuring **Heap, Linked List, Deque, Trie, Graph, Red-Black Tree, TreeMap, TreeSet, SkipList, Segment Tree**, and more — with APIs that align with JavaScript's native **Array, Map, and Set**. Zero dependencies. Type-safe. ES2025 Set operations. O(log n) rank \u0026 range queries.\n\n\u003e **Looking for a TreeMap, TreeSet, or PriorityQueue in TypeScript/JavaScript?** Familiar API, set operations, rank queries, sorted access — no more repeated `Array.sort()`.\n\n![npm](https://img.shields.io/npm/dm/data-structure-typed)\n![GitHub contributors](https://img.shields.io/github/contributors/zrwusa/data-structure-typed)\n![GITHUB Star](https://img.shields.io/github/stars/zrwusa/data-structure-typed)\n[![codecov](https://img.shields.io/codecov/c/github/zrwusa/data-structure-typed)](https://codecov.io/gh/zrwusa/data-structure-typed)\n![eslint](https://aleen42.github.io/badges/src/eslint.svg)\n![NPM](https://img.shields.io/npm/l/data-structure-typed)\n![npm](https://img.shields.io/npm/v/data-structure-typed)\n\n**📦 [Installation](#-installation) • 🎮 [Playground](#-playground) • ⚡ [Quick Start](#-quick-start-30-seconds) • 📖 [Docs](#-documentation) • 📋 [API](https://data-structure-typed-docs.vercel.app/) • 💡 [Examples](./docs/GUIDES.md) • ❓ [FAQ](#-faq)**\n\n---\n\n## Table of Contents\n\n1. [Installation](#-installation)\n2. [Playground](#-playground)\n3. [Quick Start](#-quick-start-30-seconds)\n4. [Who Should Use This?](#-who-should-use-this)\n5. [Why Not Just Array or Map?](#-why-not-just-array-or-map)\n6. [Key Features](#-key-features)\n7. [Data Structures](#-data-structures-available)\n8. [Documentation](#-documentation)\n9. [FAQ](#-faq)\n\n---\n\n## 📦 Installation\n\n```bash\nnpm i data-structure-typed\n```\n\n```bash\nyarn add data-structure-typed\n```\n\n```bash\npnpm add data-structure-typed\n```\n\n### Subpath Imports (Tree-Shaking Friendly)\n\nImport only what you need — bundlers automatically tree-shake unused code:\n\n```typescript\n// Full bundle — everything available\nimport { RedBlackTree, Deque, HashMap } from 'data-structure-typed';\n\n// Subpath — smaller bundle, only loads the category you need\nimport { RedBlackTree, TreeMap, AVLTree } from 'data-structure-typed/binary-tree';\nimport { Deque, Queue } from 'data-structure-typed/queue';\nimport { HashMap } from 'data-structure-typed/hash';\nimport { Heap, MinHeap } from 'data-structure-typed/heap';\nimport { Trie } from 'data-structure-typed/trie';\nimport { Stack } from 'data-structure-typed/stack';\nimport { DoublyLinkedList } from 'data-structure-typed/linked-list';\nimport { DirectedGraph } from 'data-structure-typed/graph';\nimport { Matrix } from 'data-structure-typed/matrix';\nimport { MinPriorityQueue } from 'data-structure-typed/priority-queue';\n```\n\n\u003e **Note:** With `\"sideEffects\": false` and modern bundlers (Vite, Webpack 5, Rollup), even the full import `from 'data-structure-typed'` will tree-shake unused structures. Subpath imports give you explicit control and faster IDE autocomplete.\n\n### Individual Packages\n\nStandalone packages are also available:\n\n```bash\nnpm i avl-tree-typed bst-typed heap-typed\n```\n\n---\n\n## 🎮 Playground\n\nTry it instantly:\n\n- [Node.js TypeScript](https://stackblitz.com/github/zrwusa/dst-playgrounds/tree/main/apps/nodejs-ts?file=src%2Findex.ts\u0026title=data-structure-typed%20%E2%80%94%20Node.js%20TypeScript)\n- [Node.js JavaScript](https://stackblitz.com/github/zrwusa/dst-playgrounds/tree/main/apps/nodejs-js?file=src%2Findex.js\u0026title=data-structure-typed%20%E2%80%94%20Node.js%20JavaScript)\n- [React TypeScript](https://stackblitz.com/github/zrwusa/dst-playgrounds/tree/main/apps/reactjs?file=src%2FApp.tsx\u0026title=data-structure-typed%20%E2%80%94%20React%20Playground)\n- [NestJS](https://stackblitz.com/github/zrwusa/dst-playgrounds/tree/main/apps/nestjs?file=src%2Fproduct%2Fservices%2Fproduct-price-index.service.ts\u0026title=data-structure-typed%20%E2%80%94%20NestJS%20Product%20API)\n\n---\n\n## 🎯 Who Should Use This?\n\n**If you are building ranked collections, scheduling queues, or sorted data structures in TypeScript,**  \n**consider `data-structure-typed` instead of hand-rolled Arrays or Maps.**\n\n### Perfect for:\n\n- **Leaderboards \u0026 Rankings** — Maintain top-K efficiently without repeated sorting\n- **Task Scheduling** — Priority queues, ordered execution, time-based operations\n- **Real-Time Dashboards** — Grafana-style workloads with instant lookups\n- **Time-Series Data** — Sorted insertion + fast range queries\n- **Search \u0026 Autocomplete** — Prefix matching at scale\n- **Graph Problems** — Pathfinding, cycle detection, topological sorting\n\n---\n\n## ⚡ Why Not Just Array or Map?\n\n| Use Case               | Array                | Map              | data-structure-typed |\n|------------------------|----------------------|------------------|:--------------------:|\n| **Sorted Lookup**      | ❌ O(n)               | ❌ Unordered      |    ✅ **O(log n)**    |\n| **Insert at Position** | ❌ O(n) shift         | ❌ No position    |    ✅ **O(log n)**    |\n| **Leaderboard Top-K**  | ❌ Re-sort O(n log n) | ❌ Manual sort    |    ✅ **Instant**     |\n| **Remove from Front**  | ❌ O(n)               | ❌ No dequeue     |      ✅ **O(1)**      |\n| **Prefix Search**      | ❌ O(n*m)             | ❌ Not applicable |    ✅ **O(m + k)**    |\n| **Familiar API**       | ✅ Yes                | ✅ Yes            |      ✅ **Same**      |\n\n### Real-World Pain Point\n\n```javascript\n// ❌ WITHOUT data-structure-typed\nconst queue = [1, 2, 3, ..., 100000\n]\n;\nfor (let i = 0; i \u003c 100000; i++) {\n  queue.shift();  // O(n) - Reindexes EVERY element!\n}\n// Time: 2829ms ❌\n```\n\n```javascript\n// ✅ WITH data-structure-typed (Deque)\nconst deque = new Deque([1, 2, 3, ..., 100000])\n;\nfor (let i = 0; i \u003c 100000; i++) {\n  deque.shift();  // O(1) - Just moves a pointer\n}\n// Time: 5.83ms ✅\n// **484x faster!**\n```\n\n---\n\n## 🚀 Performance (TL;DR)\n\n- **Optimized for V8 hot paths** (see [PERFORMANCE.md](./docs/PERFORMANCE.md) for measured benchmarks)\n  - Repeated Array.shift() O(n) → Deque O(1)\n  - Frequent update + keep-sorted workflows → RedBlackTree O(log n) operations\n  - Avoid repeated `Array.sort()` if you must maintain sorted order after each update\n\n- **Optimized for V8 JIT** (Node.js 18+, modern browsers)\n\n- **Tree-shakable** ESM / CJS / legacy builds\n\n[//]: # (No deletion!!! Start of README Performance Section)\n\n| Data Structure | Test Case | DST (ms) | Native (ms) | C++ (ms) | js-sdsl (ms) |\n|----------------|-----------|----------|-------------|----------|---------------|\n| Queue | 1M push | 26.93 | 23.83 | 1.70 | 27.59 |\n| Deque | 1M push | 9.77 | 26.81 | 1.76 | 7.79 |\n| DoublyLinkedList | 100k push | 5.70 | 2.40 | 5.70 | 1.90 |\n| SinglyLinkedList | 100K unshift \u0026 shift | 3.77 | 1958.39 | 4.80 | - |\n| PriorityQueue | 100K add | 4.00 | - | 1.05 | 4.96 |\n| TreeSet | 1M add | 995.72 | - | 462.00 | 677.58 |\n| TreeMap | 1M set | 978.72 | - | 512.00 | 623.23 |\n| TreeMultiSet | 1M add (TreeMultiSet expanded iteration) | 217.73 | - | 752.00 | - |\n| TreeMultiMap | 1M add (TreeMultiMap bucketed) | 366.19 | - | 731.00 | - |\n| RedBlackTree | 1M get | 99.24 | - | 52.97 | - |\n| BST | 10K add randomly | 5.50 | - | - | - |\n| BinaryTree | 1K add randomly | 9.77 | - | - | - |\n| HashMap | 1M set | 146.17 | 144.83 | 76.26 | 94.16 |\n| Trie | 100K add | 141.10 | - | - | - |\n| DirectedGraph | 1K addVertex | 0.05 | - | - | - |\n| Stack | 1M push | 46.38 | 30.28 | 1.65 | 32.38 |\n\n[//]: # (No deletion!!! End of README Performance Section)\n\n📊 [Full benchmarks →](./docs/PERFORMANCE.md) | [Interactive report →](./docs/benchmark.html)\n\n---\n\n## ✨ Key Features\n\n### 🏠 Uniform API\n\nDon't learn new APIs. Just use `push`, `pop`, `map`, `filter`, and `reduce` everywhere.\n\n```javascript\n// All linear structures use THE SAME 4 methods\nconst deque = new Deque([1, 2, 3]);\nconst queue = new Queue([1, 2, 3]);\nconst doublyLinkeList = new DoublyLinkedList([1, 2, 3]);\nconst singlyLinkedList = new SinglyLinkedList([1, 2, 3]);\n\n// They ALL support:\nstructure.push(item);          // Add to end\nstructure.pop();               // Remove from end\nstructure.shift();             // Remove from start\nstructure.unshift(item);       // Add to start\n```\n\n### 🛡️ Type Safe\n\nFull generics and strict TypeScript support out of the box.\n\n```typescript\nconst tree = new RedBlackTree\u003cnumber, string\u003e();\ntree.set(1, 'Alice');\ntree.set(2, 'Bob');\n\n// Type-safe access\nconst value = tree.get(1);  // Type: string | undefined\n```\n\n### ✨ Zero Friction\n\nWorks everywhere. Spread it `[...]`, loop it `for..of`, convert it instantly. Pass raw data with `toEntryFn`/`toElementFn` — no pre-processing needed.\n\n```javascript\n// All data structures work with iterator protocol\nconst tree = new RedBlackTree([5, 2, 8]);\nconst sorted = [...tree];              // Spread operator\nfor (const item of tree) {\n}           // for...of loop\nconst set = new Set(tree);             // Set constructor\n\n// Pass raw data directly\nconst map = new TreeMap(users, { toEntryFn: u =\u003e [u.id, u.name] });\n```\n\n### 🔄 Working with Raw Data\n\nGot raw objects? Three ways to use them — pick based on what you want to store:\n\n```typescript\ninterface User {\n  id: number;\n  name: string;\n}\n\nconst users: User[] = [\n  { id: 3, name: 'Charlie' },\n  { id: 1, name: 'Alice' },\n  { id: 2, name: 'Bob' }\n];\n\n// 1. Extract a field — store only that field\nconst ids = new TreeSet\u003cnumber, User\u003e(\n  users,\n  { toElementFn: u =\u003e u.id }\n);\n// [1, 2, 3] — numbers only, original objects not kept\n\n// 2. Store full objects — sort by a field\nconst fullSet = new TreeSet\u003cUser\u003e(\n  users,\n  { comparator: (a, b) =\u003e a.id - b.id }\n);\n// [{ id: 1, name: 'Alice' }, { id: 2, ... }, { id: 3, ... }]\n\n// 3. Split into key-value — field as key, anything as value\nconst map = new TreeMap\u003cnumber, User, User\u003e(\n  users,\n  { toEntryFn: u =\u003e [u.id, u] }\n);\n// map.get(1) → { id: 1, name: 'Alice' }\n```\n\nWorks across all data structures — `toElementFn` for single-value types (Heap, Queue, Stack, LinkedList, Trie), `toEntryFn` for key-value types (TreeMap, HashMap, SkipList), and `comparator` for any sorted structure.\n\n---\n\n## 💡 When Should I Consider This Library?\n\n✅ **When you need:**\n\n- Top-K / Leaderboard queries without repeated sorting\n- Insertion order + lookup performance simultaneously\n- Priority queues with fast position-based access\n- Time-series data with range queries\n- Red-Black Tree / Heap performance without learning new APIs\n- **Pass raw objects directly** — no `.map()` pre-processing needed (unique to this library in JS/TS)\n\n✅ **When your current code has:**\n\n- `array.sort()` in hot paths (request handlers, loops)\n- Manual index tracking after insertions\n- `Array.shift()` on large lists (queues)\n- Custom sorting logic you repeat across files\n- Map that needs to be ordered\n- `.map()` calls just to reshape data before putting it in a collection\n\n---\n\n## 🚀 Quick Start: 30 Seconds\n\n### Leaderboard (Ranked Collections)\n\n```typescript\nimport { RedBlackTree } from 'data-structure-typed';\n\n// Descending comparator — highest scores first\nconst leaderboard = new RedBlackTree\u003cnumber, string\u003e([\n  [100, 'Alice'],\n  [85, 'Bob'],\n  [92, 'Charlie']\n], { comparator: (a, b) =\u003e b - a });\n\n// Top-2 via lazy iterator — O(k log n), no array copy\nconst iter = leaderboard.entries();\nconst { value: [topScore, topPlayer] } = iter.next();\nconsole.log(`${topScore}: ${topPlayer}`); // 100: Alice\n\n// Update score — O(log n)\nleaderboard.delete(85);\nleaderboard.set(95, 'Bob');\n\n// Range query — players scoring 90~100, O(log n + k)\nconst scores90to100 = leaderboard.rangeSearch([90, 100]);\n// [100, 95, 92] — automatically respects tree order\n\n// For O(log n) top-k, rank, and pagination → see Order-Statistic Tree below\n```\n\n### Order-Statistic Tree (Rank Queries)\n\n```typescript\nimport { RedBlackTree } from 'data-structure-typed';\n\nconst tree = new RedBlackTree\u003cnumber, string\u003e([\n  [100, 'Alice'], [85, 'Bob'], [92, 'Charlie'],\n  [78, 'Diana'], [95, 'Eve']\n], { comparator: (a, b) =\u003e b - a, enableOrderStatistic: true });\n\n// select(k) — find k-th element, O(log n)\ntree.getByRank(0);              // 100 (1st in tree order)\ntree.getByRank(2);              // 92  (3rd in tree order)\n\n// rank(key) — count elements preceding key in tree order, O(log n)\ntree.getRank(92);               // 2 (2 elements before 92 in tree order)\n\n// rangeByRank — pagination, O(log n + k)\ntree.rangeByRank(0, 2);      // [100, 95, 92] — top 3\n\n// Also works with TreeMap, TreeSet, TreeMultiMap, TreeMultiSet\n```\n\n### Task Queue (Scheduling)\n\n```typescript\nimport { MaxPriorityQueue } from 'data-structure-typed';\n\nconst taskQueue = new MaxPriorityQueue\u003c{priority: number; task: string}\u003e([], {\n  comparator: (a, b) =\u003e b.priority - a.priority\n});\n\ntaskQueue.add({ priority: 5, task: 'Email' });\ntaskQueue.add({ priority: 9, task: 'Alert' });  // Instant priority handling\n\nconst nextTask = taskQueue.pop();  // { priority: 9, task: 'Alert' }\n```\n\n### Set Operations (ES2025)\n\n```typescript\nimport { TreeSet } from 'data-structure-typed';\n\nconst a = new TreeSet([1, 2, 3, 4, 5]);\nconst b = new TreeSet([3, 4, 5, 6, 7]);\n\n[...a.union(b)];               // [1,2,3,4,5,6,7]\n[...a.intersection(b)];        // [3,4,5]\n[...a.difference(b)];          // [1,2]\n[...a.symmetricDifference(b)]; // [1,2,6,7]\na.isSubsetOf(b);               // false\n\n// Works with any Iterable — native Set, arrays, generators\na.intersection(new Set([2, 4, 6]));  // TreeSet [2, 4]\n```\n\n### Fast Queue (FIFO)\n\n```typescript\nimport { Deque } from 'data-structure-typed';\n\nconst queue = new Deque([1, 2, 3, 4, 5]);\nqueue.shift();  // Remove from front: O(1) not O(n)\nqueue.push(6);  // Add to back: O(1)\n```\n\n---\n\n## 📊 Data Structures Available\n\n| Structure                | Use Case                          | Time Complexity | NPM                                                       |\n|--------------------------|-----------------------------------|-----------------|-----------------------------------------------------------|\n| **RedBlackTree**         | Sorted collections, range queries | O(log n)        | [npm](https://www.npmjs.com/package/red-black-tree-typed) |\n| **Heap / PriorityQueue** | Task scheduling, top-K elements   | O(log n)        | [npm](https://www.npmjs.com/package/heap-typed)           |\n| **Deque**                | Fast front/back operations        | O(1)            | [npm](https://www.npmjs.com/package/deque-typed)          |\n| **Trie**                 | Autocomplete, prefix search       | O(m+k)          | [npm](https://www.npmjs.com/package/trie-typed)           |\n| **DirectedGraph**        | Pathfinding, DAG algorithms       | O(V+E)          | [npm](https://www.npmjs.com/package/directed-graph-typed) |\n| **Stack**                | Undo/redo, expression parsing     | O(1)            | [npm](https://www.npmjs.com/package/stack-typed)          |\n| **LinkedList**           | Dynamic sizing, no index shift    | O(1)*           | [npm](https://www.npmjs.com/package/linked-list-typed)    |\n| **AVLTree**              | Stricter balance than RB-Tree     | O(log n)        | [npm](https://www.npmjs.com/package/avl-tree-typed)       |\n| **SkipList**             | Sorted KV, TreeMap alternative    | O(log n) avg    | —                                                         |\n| **SegmentTree**          | Range sum/min/max/custom queries  | O(log n)        | —                                                         |\n| **BinaryIndexedTree**    | Prefix sums, frequency counting   | O(log n)        | —                                                         |\n| **Matrix**               | 2D grid arithmetic                | O(n²) add       | —                                                         |\n\n👉 [See all 20+ structures →](./docs/OVERVIEW.md) | [Full API docs →](https://data-structure-typed-docs.vercel.app/)\n\n---\n\n## 📖 Documentation\n\n### For Different Use Cases\n\n| Your Goal                 | Start Here                                | Next Steps                              |\n|---------------------------|-------------------------------------------|-----------------------------------------|\n| **Learn concepts**        | [CONCEPTS.md](./docs/CONCEPTS.md)         | [GUIDES.md](./docs/GUIDES.md)           |\n| **Use in my project**     | [GUIDES.md](./docs/GUIDES.md)             | [OVERVIEW.md](./docs/OVERVIEW.md)       |\n| **Look up API**           | [API Docs](https://data-structure-typed-docs.vercel.app/) | [PERFORMANCE.md](./docs/PERFORMANCE.md) |\n| **Performance questions** | [PERFORMANCE.md](./docs/PERFORMANCE.md)   | [ARCHITECTURE.md](./docs/ARCHITECTURE.md)    |\n| **Framework integration** | [INTEGRATIONS.md](./docs/INTEGRATIONS.md) | [GUIDES.md](./docs/GUIDES.md)           |\n| **Understand design**     | [ARCHITECTURE.md](./docs/ARCHITECTURE.md)      | [CONCEPTS.md](./docs/CONCEPTS.md)       |\n\n### Documentation Files\n\n1. **[CONCEPTS.md](./docs/CONCEPTS.md)** - Core Fundamentals \u0026 Theory\n  - Big Three Concepts (BST, Balanced Trees, Heap)\n  - 13 Plain Language Explanations\n  - Iterator Protocol Design\n  - 5 Comparisons with Native JavaScript\n  - Complete Decision Guide\n\n2. **[API Docs](https://data-structure-typed-docs.vercel.app/)** - Full API Reference (TypeDoc)\n  - Complete method signatures, parameters, return types\n  - Real-world `@example` code for every method\n  - Inheritance hierarchy and type details\n\n3. **[OVERVIEW.md](./docs/OVERVIEW.md)** - Data Structures Overview\n  - Quick Reference Table\n  - All 20+ Structures with Examples\n  - CRUD Operations\n  - Common Methods\n  - TypeScript Support\n\n4. **[ARCHITECTURE.md](./docs/ARCHITECTURE.md)** - Design \u0026 Implementation\n  - Design Philosophy \u0026 Principles\n  - 3 Pain Points Solved\n  - Why Deque is 484x Faster\n  - Iterator Protocol Design\n  - Self-Balancing Strategy\n  - V8 JIT Optimizations\n\n5. **[PERFORMANCE.md](./docs/PERFORMANCE.md)** - Benchmarks \u0026 Comparisons\n  - Performance Summary\n  - 3 Real-World Scenarios\n  - Detailed Benchmarks\n  - When to Use What\n  - Optimization Tips\n\n6. **[GUIDES.md](./docs/GUIDES.md)** - Real-World Examples\n  - 4 Design Patterns\n  - 5 Production Code Examples\n  - Common Mistakes\n  - Best Practices\n\n7. **[INTEGRATIONS.md](./docs/INTEGRATIONS.md)** - Framework Integration\n  - React Integration (State Management, Leaderboard)\n  - Express Integration (LRU Cache, Rate Limiting)\n  - Nest.js Integration (Ranking Service, Task Queue)\n  - TypeScript Configuration\n\n---\n\n## 💻 Real-World Examples\n\n### LRU Cache\n\n```typescript\nclass LRUCache\u003cK, V\u003e {\n  private cache = new Map\u003cK, V\u003e();\n  private order = new DoublyLinkedList\u003cK\u003e();\n\n  get(key: K): V | null {\n    if (!this.cache.has(key)) return null;\n    // Move to end (recently used)\n    // Efficient with O(1) operations\n    return this.cache.get(key)!;\n  }\n}\n```\n\n### Leaderboard\n\n```typescript\n\ntype Player = {\n  id: string;\n  name: string;\n  score: number;\n};\n\nconst seedPlayers: Player[] = [\n  { id: 'player_01HZX4E8Q2K8Y3J9M7T1A6B3C4', name: 'Pablo', score: 65 },\n  { id: 'player_01HZX4E9R6V2D8K1P0N5S4T7U8', name: 'Bunny', score: 10 },\n  { id: 'player_01HZX4EA3M9Q7W1E2R8T6Y5U0I', name: 'Jeff', score: 99 },\n];\n\nclass ScoreLeaderboard {\n  private readonly byScore: RedBlackTree\u003cnumber, Player, Player\u003e;\n\n  constructor(initialPlayers: Player[]) {\n    this.byScore = new RedBlackTree\u003cnumber, Player, Player\u003e(initialPlayers, {\n      isMapMode: false,// Use \"node value\" storage rather than Map-style.\n      toEntryFn: (player) =\u003e [player.score, player], // Convert a player object into the tree entry: key = score, value = player.\n    });\n  }\n\n  /**\n   * Returns players whose scores fall within the given range.\n   * Supports either a tuple [min, max] or a Range object for inclusive/exclusive bounds.\n   */\n  public findPlayersByScoreRange(range: [number, number] | Range\u003cnumber\u003e): (Player | undefined)[] {\n    return this.byScore.rangeSearch(range, (node) =\u003e node.value);\n  }\n  \n  public upsertPlayer(player: Player) {\n    return this.byScore.set(player.score, player);\n  }\n}\n\nconst leaderboard = new ScoreLeaderboard(seedPlayers);\n\nconsole.log(leaderboard.findPlayersByScoreRange([65, 100]));\n\nleaderboard.upsertPlayer({\n  id: 'player_01HZX4EB7C4N2M9Q8R1T3Y6U5I',\n  name: 'Alex',\n  score: 80,\n});\n\nconsole.log(leaderboard.findPlayersByScoreRange(new Range(65, 100, true, true)));\n```\n\n### Message Queue\n\n```typescript\ntype Message = {\n  id: string;\n  type: string;\n  payload: unknown;\n  priority: 'urgent' | 'normal';\n  createdAt: number;\n  retryCount?: number;\n};\n\nclass MessageQueue {\n  private urgent = new Deque\u003cMessage\u003e();\n  private normal = new Deque\u003cMessage\u003e();\n\n  dequeue(): Message | null {\n    return this.urgent.shift() || this.normal.shift();\n  }\n}\n```\n\n👉 [More examples in GUIDES.md](./docs/GUIDES.md)\n\n---\n\n## 🎯 Use Cases by Industry\n\n### 📊 Finance\n\n- Price-sorted order book\n- Real-time portfolio rankings\n- Option chain ordering\n\n### 🎮 Gaming\n\n- Player leaderboards\n- Enemy priority queues\n- Game event scheduling\n\n### 📱 Social Media\n\n- Trending posts (top-K)\n- Feed ordering\n- Notification scheduling\n\n### 🏥 Healthcare\n\n- Patient priority queues\n- Appointment scheduling\n- Medical record organization\n\n### 🛒 E-commerce\n\n- Product price ranges\n- Inventory management\n- Order scheduling\n\n---\n\n## ✨ Why Developers Love This\n\n| Pain Point                         | Solution                                  |\n|------------------------------------|-------------------------------------------|\n| Repeated sorting slowing down code | TreeSet auto-maintains order              |\n| Array.shift timeout in loops       | Deque O(1) shift instead of O(n)          |\n| Learning different APIs            | All structures use push/pop/shift/unshift |\n| Type safety nightmares             | Full TypeScript generics support          |\n| Browser compatibility issues       | Works everywhere: Node, browsers, CDN     |\n\n---\n\n## 📦 What You Get\n\n✅ **20+ data structures** (production-ready)  \n✅ **50+ code examples** (real-world patterns)  \n✅ **Full TypeScript support** (strict typing)  \n✅ **Performance benchmarks** (484x speedups)  \n✅ **Framework integrations** (React, Express, Nest.js)  \n✅ **6 core documentation files** (2500+ lines)\n\n---\n\n## 🚀 Getting Started\n\n### Step 1: Install\n\n```bash\nnpm i data-structure-typed\n```\n\n### Step 2: Import\n\n```typescript\nimport { RedBlackTree, Deque, MaxPriorityQueue } from 'data-structure-typed';\n```\n\n### Step 3: Use\n\n```typescript\nconst tree = new RedBlackTree([5, 2, 8]);\nconsole.log([...tree]);  // [2, 5, 8] - Automatically sorted!\n```\n\n## 📊 Comparison Chart\n\n```\nNeed frequent head/tail operations?\n  → Deque (O(1) shift/unshift/push/pop)\n\nNeed sorted + fast lookup?\n  → RedBlackTree (O(log n) guaranteed)\n\nNeed highest/lowest priority?\n  → Heap/PriorityQueue (O(log n) add/remove)\n\nNeed prefix/text matching?\n  → Trie (O(m+k) where m=prefix)\n\nNeed graph operations?\n  → DirectedGraph/UndirectedGraph\n\nNeed range queries on array (sum/min/max)?\n  → SegmentTree (any merge op) or BinaryIndexedTree (prefix sums only)\n\nNeed sorted key-value with same API as TreeMap?\n  → SkipList (O(log n) avg, probabilistic balancing)\n\nOtherwise?\n  → Use Array (simplest case)\n```\n\n---\n\n## 🤝 Contributing\n\nFound a bug? Have suggestions? [Open an issue](https://github.com/zrwusa/data-structure-typed/issues)\n\n---\n\n## 📄 License\n\nMIT\n\n---\n\n## 📚 Full Documentation Structure\n\n```\nREADME.md (this file)\ndocs/\n├── CONCEPTS.md (theory \u0026 fundamentals)\n├── OVERVIEW.md (Data structures overview)\n├── ARCHITECTURE.md (design principles)\n├── PERFORMANCE.md (benchmarks)\n├── GUIDES.md (real-world examples)\n└── INTEGRATIONS.md (framework guides)\n```\n\n---\n\n## 🎓 Learn More\n\n**Just started?** → [Quick Start](#-quick-start-30-seconds)\n\n**Need concepts?** → [CONCEPTS.md](./docs/CONCEPTS.md)\n\n**Want to build?** → [GUIDES.md](./docs/GUIDES.md)\n\n**Need API?** → [API Docs](https://data-structure-typed-docs.vercel.app/) | [Overview](./docs/OVERVIEW.md)\n\n**Curious about performance?** → [PERFORMANCE.md](./docs/PERFORMANCE.md)\n\n**Framework questions?** → [INTEGRATIONS.md](./docs/INTEGRATIONS.md)\n\n---\n\n**Ready to supercharge your TypeScript data structures? [Get started now →](#-quick-start-30-seconds)**\n\n---\n\n## ❓ FAQ\n\n### Does JavaScript have a TreeMap or TreeSet?\n\nNot natively. JavaScript's `Map` and `Set` are hash-based (unordered). This library provides `TreeMap` and `TreeSet` backed by Red-Black Trees — offering sorted iteration, `floor`/`ceiling`/`higher`/`lower` lookups, and `getRank`/`getByRank`/`rangeByRank` queries.\n\n### When should I use a Heap instead of sorting an array?\n\nWhen you need to repeatedly access the smallest or largest element. Sorting an array is O(n log n) every time; a Heap gives you O(log n) insert and O(1) access to the top element. Use `Heap`, `MinHeap`, or `MaxHeap` for priority queues, top-k problems, and scheduling.\n\n### Does this library support rank and range queries?\n\nYes. Enable with `{ enableOrderStatistic: true }` on any tree-based structure (RedBlackTree, TreeMap, TreeSet, etc.):\n- `getRank(key)` — how many elements precede this key in tree order\n- `getByRank(k)` — get the element at position k\n- `rangeByRank(start, end)` — get all elements between two positions\n\n### Is it faster than native arrays for ordered operations?\n\nFor ordered insert + lookup: yes. Array insert into sorted position is O(n) (shift elements). Red-Black Tree insert is O(log n). For 10,000+ elements, the difference is significant. See [PERFORMANCE.md](./docs/PERFORMANCE.md) for benchmarks.\n\n### Can I use this in React / Node.js / browser?\n\nYes. The library ships ESM, CJS, and UMD builds. It works in Node.js, browsers, React, Vue, Angular, Next.js, and any JavaScript runtime. Zero dependencies means no compatibility concerns.\n\n### What data structures are included?\n\nHeap, MinHeap, MaxHeap, Priority Queue, Deque, Queue, Stack, Linked List (Singly / Doubly), Red-Black Tree, AVL Tree, BST, TreeMap, TreeSet, TreeMultiMap, TreeMultiSet, SkipList, Trie, HashMap, Graph (Directed / Undirected), Segment Tree, Binary Indexed Tree (Fenwick Tree), Matrix. See [full list](#-data-structures-available).\n\n### Is this library production-ready?\n\nYes. 2600+ tests, 99%+ code coverage, zero dependencies, and used in production. Every release passes typecheck, lint, and full test suite.\n\n### How does this compare to js-sdsl or other libraries?\n\n`data-structure-typed` offers more data structures (20+), a unified Array-like API across all structures, tree-shakeable subpath exports, and active maintenance. See [PERFORMANCE.md](./docs/PERFORMANCE.md) for benchmark comparisons.\n\n### Can I pass raw data without converting it first?\n\nYes. Three patterns:\n- **`toElementFn`** — extract a field, store only that (TreeSet, Heap, Queue, Stack, LinkedList, Trie)\n- **`comparator`** — store full objects, sort by a field (all sorted structures)\n- **`toEntryFn`** — split into key-value pairs (TreeMap, HashMap, SkipList)\n\nSee the [Raw Data section](#-working-with-raw-data) for examples.\n\n### What is the bundle size?\n\nUMD bundle: ~143KB minified. With subpath imports (e.g., `data-structure-typed/heap`), you only load what you use — as small as 18KB for Stack, 30KB for Heap. `sideEffects: false` enables full tree-shaking.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzrwusa%2Fdata-structure-typed","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzrwusa%2Fdata-structure-typed","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzrwusa%2Fdata-structure-typed/lists"}