TypeScript Stack with Generics

1.0.4 · active · verified Sun Apr 19

stack-typescript is a lightweight, generic Stack data structure implementation for TypeScript and JavaScript environments, currently at version 1.0.4. It is built upon the `linked-list-typescript` package, providing a LIFO (Last-In, First-Out) collection. Key features include full TypeScript generics support for strong type-checking, enabling stacks of any primitive, object, or custom class. The package also implements both the JavaScript iterator and iterable protocols, allowing seamless integration with `for...of` loops, spread syntax (`...`), and array deconstruction. Its primary differentiators are its explicit use of a linked list for underlying storage and its full adherence to TypeScript's type-templating capabilities, ensuring type safety from initialization to manipulation. The release cadence appears stable, with a focus on core data structure functionality without frequent breaking changes, typical for foundational utility libraries.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating, initializing, pushing, peeking, popping, and iterating a Stack with both primitive and custom types.

import { Stack } from 'stack-typescript';

// Create an empty stack of numbers
let numberStack = new Stack<number>();
numberStack.push(10);
numberStack.push(20);
numberStack.push(30);

console.log(`Number Stack Size: ${numberStack.size}`); // Expected: 3
console.log(`Top of Number Stack: ${numberStack.top}`); // Expected: 30

// Initialize a stack with values and custom types
class Foo {
  constructor(public val: number) {}
  get bar(): number { return this.val; }
}

let foo1 = new Foo(100);
let foo2 = new Foo(200);
let fooStack = new Stack<Foo>(foo1, foo2, new Foo(300));

console.log(`Foo Stack Size: ${fooStack.size}`); // Expected: 3
console.log(`Top of Foo Stack: ${fooStack.top?.bar}`); // Expected: 100

let poppedFoo = fooStack.pop();
console.log(`Popped Foo: ${poppedFoo?.bar}`); // Expected: 100
console.log(`Foo Stack Size after pop: ${fooStack.size}`); // Expected: 2

// Iterate over the stack
console.log('Iterating over Foo Stack:');
for (let item of fooStack) {
  console.log(item.bar);
}
// Expected: 200, 300

view raw JSON →