A TypeScript implementation of a stack data structure following the LIFO (Last-In, First-Out) principle.
- using
npm
npm install @caelus-dts/stack
- using
yarn
yarn add @caelus-dts/stack
- using
pnpm
pnpm add @caelus-dts/stack
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
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 (===
).
-
isEmpty
: Returnstrue
if the stack is empty,false
otherwise. -
size
: Returns the number of elements in the stack.
-
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. Returnsundefined
if the stack is empty. -
peek()
: Returns the element at the start of the stack without removing it. Returnsundefined
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.
Contributions are welcome! Please fork the repository and submit a pull request.