@caelus-dts/stack
TypeScript icon, indicating that this package has built-in type declarations

0.1.0 • Public • Published

@caelus-dts/stack

Overview

A TypeScript implementation of a stack data structure following the LIFO (Last-In, First-Out) principle.

Installation

  • using npm
npm install @caelus-dts/stack
  • using yarn
yarn add @caelus-dts/stack
  • using pnpm
pnpm add @caelus-dts/stack

Usage

import Stack from '@caelus-dts/stack';

const stack = new Stack<number>();

stack.push(10, 20, 30);

console.log(stack.pop()); // Output: 30
console.log(stack.peek()); // Output: 10
console.log(stack.size); // Output: 2
console.log(stack.isEmpty); // Output: false

stack.clear();
console.log(stack.isEmpty); // Output: true


const values = [1, 2, 3, 4, 5, 5];
const stack2 = new Stack(values);

console.log(stack2.toArray()) // Output: [1, 2, 3, 4, 5, 5]
console.log(stack2.contains(1)) // Output: true
console.log(stack2.contains(10)) // Output: false

const stack3 = new Stack([1, 2, 3]);
console.log(stack2.equals(stack3)); // Output: false

API Documentation

Constructor

new Stack<T>(values?: Iterable<T>, compareFunc?: CompareFunc<T>) Creates a new Stack instance.

  • values: Optional iterable of values to pre-populate the stack.
  • compareFunc: Optional comparison function used to compare elements in the stack. Defaults to strict equality (===).

Properties

  • isEmpty: Returns true if the stack is empty, false otherwise.
  • size: Returns the number of elements in the stack.

Methods

  • push(...items: T[]): Adds items to the end of the stack. Returns the stack instance for chaining.
  • pop(): Removes and returns the element at the end of the stack. Returns undefined if the stack is empty.
  • peek(): Returns the element at the start of the stack without removing it. Returns undefined if the stack is empty.
  • clear(): Removes all elements from the stack.
  • indexOf(item: T): Checks if the stack contains a specific element.
  • contains(item: T): Checks if the stack contains a specific element.
  • getAt(index: number): Retrieves the element at the specified index from the list.
  • removeAt(index: number): Removes an element from the list at the specified index.
  • remove(item: T): Removes the specified element from the list if it is present.
  • toArray(): Returns an array containing all elements in the stack.
  • equals(stack: Stack<T>): Checks if the current stack is equal to another stack.

Contributing

Contributions are welcome! Please fork the repository and submit a pull request.

License

MIT License

Package Sidebar

Install

npm i @caelus-dts/stack

Weekly Downloads

2

Version

0.1.0

License

MIT

Unpacked Size

13.8 kB

Total Files

6

Last publish

Collaborators

  • caelus-lib