Skip to content

Instantly share code, notes, and snippets.

@frydlewicz
Last active July 27, 2020 16:16
Show Gist options
  • Save frydlewicz/4ff8d0ed7fd22174604fafaffc05e950 to your computer and use it in GitHub Desktop.
Save frydlewicz/4ff8d0ed7fd22174604fafaffc05e950 to your computer and use it in GitHub Desktop.
Stack TypeScript class with build-in iterator
export default class Stack<T> {
private readonly maxSize: number;
private readonly loop: boolean;
private readonly data: T[];
private pos!: number;
constructor(maxSize: number, loop: boolean = false) {
if (!Number.isInteger(maxSize) || maxSize < 1) {
throw new Error('Invalid parameter');
}
this.maxSize = maxSize;
this.loop = loop;
this.data = new Array(maxSize);
this.clear();
}
public push(value: T): void {
if (this.pos > this.maxSize - 2) {
if (!this.loop) {
throw new Error('Stack overflow');
}
this.pop();
}
this.data[++this.pos] = value;
}
public pop(): T {
if (this.pos < 0) {
throw new Error('Stack empty');
}
return this.data[this.pos--];
}
public top(): T | undefined {
if (this.pos < 0) {
return undefined;
}
return this.data[this.pos];
}
public getSize(): number {
return this.pos + 1;
}
public isEmpty(): boolean {
return this.getSize() <= 0;
}
public clear(): void {
this.pos = -1;
}
public [Symbol.iterator](): Iterator<T> {
const data = this.data;
let pos = this.pos;
return {
next(): IteratorResult<T> {
if (pos < 0) {
return {
done: true,
value: null,
};
}
return {
done: false,
value: data[pos--],
};
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment