Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Last active March 1, 2023 18:37
Show Gist options
  • Save anushshukla/b7df26740771259ac44815340d23c6ff to your computer and use it in GitHub Desktop.
Save anushshukla/b7df26740771259ac44815340d23c6ff to your computer and use it in GitHub Desktop.
Data structures in Typescript
class Queue<T> {
_size: number;
_data = [] as T[];
public constructor(size: number) {
this._size = size;
}
public enqueue(element: T): void {
if (this._data.length === this._size) {
throw new Error('Queue overflow detected!');
}
this._data.push(element);
}
public dequeue(): void {
this._data.shift();
}
public head(): T {
return this._data[0];
}
public tail(): T {
return this._data[this._data.length - 1];
}
}
class Stack<T> {
_size: number;
_data = [] as T[];
public constructor(size: number) {
this._size = size;
}
public push(element: T): void {
if (this._data.length === this._size) {
throw new Error('Stack overflow detected!');
}
this._data.push(element);
}
public pop(): void {
this._data.pop();
}
public bottom(): T {
return this._data[0];
}
public top(): T {
return this._data[this._data.length - 1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment