A comprehensive TypeScript data structures library with production-ready implementations.
📚 Installation • Quick Start • Full Docs • API Reference • Playground • Examples
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.
| 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 |
// ❌ 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!**
10–40% faster than common JS implementations in hot paths
Optimized for V8 JIT (Node.js 18+, modern browsers)
Tree-shakable ESM / CJS / legacy builds
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
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
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
pnpm add data-structure-typed
npm i data-structure-typed --save
yarn add data-structure-typed
Use only what you need:
pnpm add heap-typed deque-typed red-black-tree-typed
✅ When you need:
✅ When your current code has:
array.sort() in hot paths (request handlers, loops)Array.shift() on large lists (queues)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);
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' }
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)
| 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 |
| 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 |
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)!;
}
}
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)));
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();
}
}
| 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 |
✅ 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)
npm i data-structure-typed
import { RedBlackTree, Deque, MaxPriorityQueue } from 'data-structure-typed';
const tree = new RedBlackTree([5, 2, 8]);
console.log([...tree]); // [2, 5, 8] - Automatically sorted!
🏃🏻♀️ Try it instantly:
👉 Check CONCEPTS.md for core concepts
👉 See GUIDES.md for production examples
👉 Read REFERENCE.md for complete API
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)
Found a bug? Have suggestions? Open an issue
MIT
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)
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 →