circular-stack
A fixed-size auto-overwriting stack implementation.
Highlights
- Supports TypeScript!
- Supports Node and browser
- Includes full JSDoc documentation
- Very lightweight!
- Contains tests
Installation
NodeJS
npm install circular-stack --save
Browser
Import the script:
<script src="https://joker876.github.io/circular-stack/circular-stack.min.js">
And import the class from a global object:
new CircularStack.CircularStack();
Usage
import CircularStack from 'circular-stack';
Constructor
new CircularStack<T = any>(capacity: number);
CircularStack constructor takes the stack's maximum capacity as its only argument. Capacity is optional, and defaults to 100
.
The type of the elements can also be specified explicitly. The default type is any
.
const stack = new CircularStack(50);
const stack = new CircularStack<number>(50);
Members
size
- the amount of elements on the stack.capacity
- the meximum number of elements on the stack. Exceeding this value will cause the elements to be overwritten when pushed.
Methods
push
stack.push(item: T): void
Pushes a new item onto the stack.
If the size of the stack reaches the capacity, it overwrites the oldest item.
stack.push(5);
pop
stack.pop(): T | undefined
Removes the top element on the stack, and returns it.
If the stack is empty, returns undefined
.
stack.push(1);
stack.push(2);
stack.push(3);
stack.pop();
stack.pop();
stack.pop();
stack.pop();
peek
stack.peek(): T | undefined
Returns the top element of the stack without removing it.
If the stack is empty, returns undefined
.
stack.push(1);
stack.peek();
stack.peek();
clear
stack.clear(): void
Clears all elements from the stack.
stack.push(1);
stack.push(2);
stack.push(3);
stack.clear();
stack.peek();