TypeScript Collections

1.3.3 · maintenance · verified Sun Apr 19

typescript-collections is a robust and fully tested data structure library written in TypeScript, currently at version 1.3.3. It provides a comprehensive suite of common data structures, including Linked Lists, Dictionaries (regular, multi, and default), Binary Search Trees, Stacks, Queues, Sets, Bags, Binary Heaps, and Priority Queues, alongside array utility functions. The library leverages TypeScript Generics to offer strong type safety and enhanced developer experience through IntelliSense. It supports UMD (Universal Module Definition), making it suitable for use in Node.js, modern browsers, and other JavaScript environments. A key design aspect for its hashing-based collections (like `Dictionary` and `Set`) is the reliance on an item's `toString()` method for equality checks, necessitating custom implementations for non-primitive keys to ensure correct behavior. The package was last published 6 years ago, suggesting it is in a maintenance phase with infrequent updates.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic usage of `Set` and `Queue` with generics for type safety, and illustrates how to use custom objects as keys in a `Dictionary` by implementing a `toString()` method for proper hashing.

import * as Collections from 'typescript-collections';

// Demonstrate Set usage with generics for type safety
var mySet = new Collections.Set<number>();
mySet.add(123);
mySet.add(456);
mySet.add(123); // Duplicate, will not be added to the set

console.log(`Set size: ${mySet.size()}`); // Expected output: Set size: 2
console.log(`Set contains 456: ${mySet.contains(456)}`); // Expected output: Set contains 456: true

// Demonstrate Queue usage
var myQueue = new Collections.Queue<string>();
myQueue.enqueue("first");
myQueue.enqueue("second");

console.log(`Dequeued: ${myQueue.dequeue()}`); // Expected output: Dequeued: first
console.log(`Dequeued: ${myQueue.dequeue()}`); // Expected output: Dequeued: second
console.log(`Queue is empty: ${myQueue.isEmpty()}`); // Expected output: Queue is empty: true

// Example of custom object as a key in a Dictionary, requiring custom toString()
class User {
    constructor(public id: number, public name: string) {}
    toString() { // Crucial for correct hashing behavior in Collections.Dictionary/Set
        return `User-${this.id}`;
    }
}

const userDict = new Collections.Dictionary<User, string>();
const user1 = new User(1, "Alice");
const user2 = new User(2, "Bob");
userDict.setValue(user1, "Administrator");
userDict.setValue(user2, "Guest");

console.log(`User 1 role: ${userDict.getValue(user1)}`); // Expected output: User 1 role: Administrator

view raw JSON →