Stack is a data structure that can be used to store and manipulate a list of elements in a LIFO (last in, first out) fashion.
Stack initialization is done by passing an array of elements to the constructor. Second parameter contains stack options
Options
Name | Description | Type | Default value |
---|---|---|---|
size | Size of the stack | number | Infinity |
strictSize | Sets size to be maximum size. Throws an error while attempt to push to full stack | boolean | false |
Stack(items?: Array<T> | T, options: TStackOptions = defaultOptions)
const stack = new Stack(
[1, 2, 3],
{
size: 5,
strictSize: true,
}
);
Push an element to the stack.
stack.push(4); // stack: [1, 2, 3, 4]
Pop an element from the stack.
stack.pop(); // returns 4, stack: [1, 2, 3]
Check if the stack is empty.
stack.isEmpty(); // false
Check if the stack is full.
stack.isFull(); // false
Peek the last element of the stack without removing it.
stack.peek(); // returns 3, stack: [1, 2, 3]
Swaps the two elements from the params.
stack.swap(1, 2); // stack: [2, 1, 3]
Swaps the two elements from the params by their indexes.
stack.swapByIndex(0, 1); // stack: [1, 2, 3]
Name | Returns |
---|---|
items | Array of items in the stack |
size | Size of the stack |
strictSize | Is array strict size |