TypeScript Linked List

1.0.15 · active · verified Sun Apr 19

The `linked-list-typescript` package provides a straightforward, type-safe implementation of a doubly linked list in TypeScript. Currently stable at version 1.0.15, it emphasizes simplicity and strong typing through TypeScript generics. The library supports the JavaScript `Iterator` and `Iterable` protocols, enabling native iteration via `for...of` loops, spread syntax (`...`), and array destructuring. Key operations like retrieving head/tail elements, and removing head/tail are available. Unlike some data structures, it stores references to values rather than copies, which is important for understanding its behavior with mutable objects. The project appears to be in an active maintenance phase, with a focus on a stable 1.x release line.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to create a generic linked list, initialize it with values, iterate over its elements, deconstruct, and perform basic operations like removing the head, including usage with custom types.

import { LinkedList } from 'linked-list-typescript';

// Create a new linked list initialized with number values
let numberList = new LinkedList<number>(10, 20, 30);

console.log(`List length: ${numberList.length}`);
console.log(`Head value: ${numberList.head}`);
console.log(`Tail value: ${numberList.tail}`);

console.log("Iterating through the list using for...of:");
for (const item of numberList) {
    console.log(item);
}

// Deconstruct elements
let [first, second] = numberList;
console.log(`Destructured: first=${first}, second=${second}`);

// Remove an element from the head
const removed = numberList.removeHead();
console.log(`Removed head: ${removed}`);
console.log(`New head: ${numberList.head}`);

// Example with a custom type
class Item {
    constructor(public id: number, public name: string) {}
}
let item1 = new Item(1, "Apple");
let item2 = new Item(2, "Banana");

let itemList = new LinkedList<Item>(item1, item2);
console.log(`Custom type list head: ${itemList.head?.name}`); // Accessing property safely

view raw JSON →