{"name":"data-structure-typed","version":"2.1.0","keywords":["data","structure","structures","data structure","datastructure","data-structure","data structures","datastructures","data-structures","in data structures","in data structure","binary","depth","breadth","first","search","index","avl","red","black","redblack","RB","segment","prefix","tree","multi","map","set","multiset","multimap","directed","undirected","graph","min","max","heap","priority","queue","singly","doubly","linked","list","js","ts","javascript","typscript","Node.js","NodeJS","c++","std","C++ STL","c++stl","C++ std","stl","std::","Python","collections","Python Collections","pythoncollections","python-collections","C#","System.Collections.Generic","collection","java.util","Java","util","binary search tree","binarysearchtree","binary-search-tree","BST","binary tree","binarytree","binary-tree","red black tree","redblacktree","redblack tree","red-black-tree","redblack-tree","trie","prefix tree","prefixtree","prefix-tree","avl tree","avltree","avl-tree","tree set","treeset","tree-set","tree multiset","treemultiset","tree-multiset","tree map","treemap","tree-map","tree multimap","treemultimap","tree-multimap","binary indexed tree","binaryindexedtree","binary-indexed-tree","segment tree","segmenttree","segment-tree","sort","sorted","order","ordered","algorithm","morris","Morris","bellman ford","bellmanford","bellman-ford","dijkstra","Dijkstra","floyd warshall","floydwarshall","floyd-warshall","tarjan","tarjan's","dfs","depth first Search","depthfirstSearch","depth-first-Search","bfs","breadth first search","breadthfirstsearch","dfs iterative","recursive","iterative","directed graph","directedgraph","directed-graph","undirected graph","undirectedgraph","undirected-graph","min heap","minheap","min-heap","max heap","maxheap","max-heap","priority queue","priorityqueue","priority-queue","max priority queue","maxpriorityqueue","max-priority-queue","min priority queue","minpriorityqueue","min-priority-queue","hash","map","hash map","hashmap","hash-map","deque","linked list","linkedlist","linked-list","singly linked list","singlylinkedlist","singly-linked-list","doubly linked list","doublylinkedlist","doubly-linked-list","stack","CommonJS","ES6","UMD","ES Modules","ESModules","ESModule"],"author":{"name":"Pablo Zeng","email":"zrwusa@gmail.com"},"license":"MIT","_id":"data-structure-typed@2.1.0","maintainers":[{"name":"zrwusa.org","email":"zrwusa@gmail.com"}],"homepage":"https://data-structure-typed-docs.vercel.app","bugs":{"url":"https://github.com/zrwusa/data-structure-typed/issues"},"dist":{"shasum":"91ee00499dfe2b45bf5a0dee1c94288ff0128223","tarball":"http://registry-npm.ywwl.com/data-structure-typed/download/data-structure-typed-2.1.0.tgz","fileCount":911,"integrity":"sha512-Cp5+nIEgeRd14l/yUqN/6McpZpwax0yeeWAbipqAhv8HSefA4xUN1CNoju8DZ1Q2LESWxCI9xvMek3ce1xY5MQ==","signatures":[{"sig":"MEUCIQCmCVMjH9/7rCze3GneUTfpwbs2QlDNsWzEmQe+WfsHKAIgBVOskUrhlScZwn5jZbSnXis5RAFsRs+0mOjewzeim9I=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":5672187,"size":902935,"noattachment":false,"key":"/data-structure-typed/-/data-structure-typed-2.1.0.tgz"},"main":"dist/cjs/index.js","types":"dist/esm/index.d.ts","module":"dist/esm/index.js","browser":"dist/umd/data-structure-typed.min.js","exports":{".":{"import":"./dist/esm/index.js","require":"./dist/cjs/index.js"}},"gitHead":"cb6bbddb719a75b3308741a64f1a88467800434b","scripts":{"ci":"env && git fetch --tags && npm run update:subs && npm run inspect && npm run lint && npm run test && npm run changelog","toc":"doctoc README.md","lint":"npm run lint:src && npm run lint:test","test":"npm run test:in-band","build":"npm run build:ecu && npm run build:docs-class","check":"tsc --noEmit","format":"npm run format:src && npm run format:test","inspect":"npm run build && npm run check && npm run lint","lint:src":"eslint --fix 'src/**/*.{js,ts}'","build:cjs":"rm -rf dist/cjs && tsc -p tsconfig-cjs.json","build:ecu":"npm run build:esm && npm run build:cjs && npm run build:umd","build:esm":"rm -rf dist/esm && tsc -p tsconfig-esm.json","build:umd":"tsup","changelog":"auto-changelog","lint:test":"eslint --fix 'test/**/*.{js,ts}'","test:perf":"npm run build:cjs && npm run build:esm && ts-node test/performance/benchmark-runner.ts --isolate --gc --cooldown-ms=80","build:docs":"npm run gen:examples && typedoc --out docs ./src","format:src":"prettier --write 'src/**/*.{js,ts}'","format:test":"prettier --write 'test/**/*.{js,ts}'","publish:all":"npm run ci && npm publish && npm run publish:docs && npm run check:exist-latest && npm run publish:subs","update:subs":"npm i avl-tree-typed binary-tree-typed bst-typed heap-typed data-structure-typed --save-dev","copy:to-subs":"sh scripts/copy_to_all_subs.sh","gen:examples":"ts-node scripts/testToExample.ts","publish:docs":"sh scripts/publish_docs.sh","publish:subs":"npm run copy:to-subs && sh scripts/publish_all_subs.sh","test:in-band":"jest --runInBand","coverage:badge":"istanbul-badges-readme","build:docs-class":"npm run gen:examples && typedoc --out docs ./src/data-structures","install:all-subs":"npm i avl-tree-typed binary-tree-typed bst-typed deque-typed directed-graph-typed doubly-linked-list-typed graph-typed heap-typed linked-list-typed max-heap-typed max-priority-queue-typed min-heap-typed min-priority-queue-typed priority-queue-typed singly-linked-list-typed stack-typed tree-multimap-typed trie-typed undirected-graph-typed queue-typed --save-dev","test:integration":"npm run update:subs && jest --config jest.integration.config.js && tsc test/integration/compile.ts && node test/integration/compile.mjs","check:exist-latest":"sh scripts/check_exist_remotely.sh","check:circular-refs":"dependency-cruiser src"},"_npmUser":{"name":"zrwusa.org","email":"zrwusa@gmail.com"},"umd:main":"dist/umd/data-structure-typed.min.js","repository":{"url":"git+https://github.com/zrwusa/data-structure-typed.git","type":"git"},"_npmVersion":"10.9.3","description":"Standard data structure","directories":{},"_nodeVersion":"22.19.0","publishConfig":{"@zrwusa:registry":"https://npm.pkg.github.com"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^29.7.0","tsup":"^8.3.5","doctoc":"^2.2.1","eslint":"^9.13.0","js-sdsl":"^4.4.2","ts-jest":"^29.2.5","ts-node":"^10.9.2","typedoc":"^0.26.10","prettier":"^3.3.3","@swc/core":"^1.7.40","benchmark":"^2.1.4","bst-typed":"^1.54.3","fast-glob":"^3.3.2","ts-loader":"^9.5.1","@eslint/js":"^9.13.0","heap-typed":"^1.54.3","typescript":"^5.6.3","@types/jest":"^29.5.14","@types/node":"^22.8.2","@eslint/compat":"^1.2.2","auto-changelog":"^2.5.0","avl-tree-typed":"^1.54.3","@eslint/eslintrc":"^3.1.0","@types/benchmark":"^2.1.5","binary-tree-typed":"^1.54.3","dependency-cruiser":"^16.5.0","data-structure-typed":"^1.54.3","eslint-plugin-import":"^2.31.0","eslint-config-prettier":"^9.1.0","istanbul-badges-readme":"^1.9.0","@typescript-eslint/parser":"^8.12.1","eslint-import-resolver-alias":"^1.1.2","@typescript-eslint/eslint-plugin":"^8.12.1","eslint-import-resolver-typescript":"^3.6.3"},"_npmOperationalInternal":{"tmp":"tmp/data-structure-typed_2.1.0_1761124261543_0.4910338394525322","host":"s3://npm-registry-packages-npm-production"},"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 & range queries.\n\n> **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> **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&title=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&title=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&title=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&title=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 & 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 & 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 < 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 < 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 & 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<number, string>();\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 => [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<number, User>(\n  users,\n  { toElementFn: u => 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<User>(\n  users,\n  { comparator: (a, b) => 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<number, User, User>(\n  users,\n  { toEntryFn: u => [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<number, string>([\n  [100, 'Alice'],\n  [85, 'Bob'],\n  [92, 'Charlie']\n], { comparator: (a, b) => 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<number, string>([\n  [100, 'Alice'], [85, 'Bob'], [92, 'Charlie'],\n  [78, 'Diana'], [95, 'Eve']\n], { comparator: (a, b) => 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<{priority: number; task: string}>([], {\n  comparator: (a, b) => 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 & 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 & Implementation\n  - Design Philosophy & 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 & 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<K, V> {\n  private cache = new Map<K, V>();\n  private order = new DoublyLinkedList<K>();\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<number, Player, Player>;\n\n  constructor(initialPlayers: Player[]) {\n    this.byScore = new RedBlackTree<number, Player, Player>(initialPlayers, {\n      isMapMode: false,// Use \"node value\" storage rather than Map-style.\n      toEntryFn: (player) => [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<number>): (Player | undefined)[] {\n    return this.byScore.rangeSearch(range, (node) => 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<Message>();\n  private normal = new Deque<Message>();\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 & 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","publish_time":1761124261762,"_cnpm_publish_time":1761124261762,"dist-tags":{"latest":"2.6.4"}}