Skip to content

Instantly share code, notes, and snippets.

@arastu
Last active March 6, 2022 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arastu/22d06e3dd0fe0197aa0a547b587b215c to your computer and use it in GitHub Desktop.
Save arastu/22d06e3dd0fe0197aa0a547b587b215c to your computer and use it in GitHub Desktop.
Simple Queue data structure in TypeScript
class Queue<T> {
private list: T[] = [];
private readonly capacity: number | null = null;
private tail = 0;
private head = 0;
constructor(capacity: number) {
this.capacity = Math.max(capacity, 0) || null;
if (this.capacity) {
this.list = Array.from<T>({ length: this.capacity });
}
}
get size(): number {
return this.tail - this.head;
}
get isEmpty(): boolean {
return this.size === 0;
}
get isFull(): boolean {
if (this.capacity) {
return this.tail === this.capacity;
}
return false;
}
enqueue(item: T) {
if (!this.isFull) {
this.list[this.tail] = item;
this.tail += 1;
}
return this.size;
}
dequeue() {
let item = null;
if (!this.isEmpty) {
item = this.list[this.head];
delete this.list[this.head];
this.head += 1;
if (this.isEmpty) {
this.head = 0;
this.tail = 0;
}
}
return item;
}
peek() {
if (this.isEmpty) {
return null;
}
return this.list[this.head];
}
clear() {
if (this.capacity) {
this.list = Array.from<T>({ length: this.capacity });
} else {
this.list = [];
}
this.head = 0;
this.tail = 0;
}
print() {
const list: T[] = [];
this.list.forEach((item) => {
list.push(item);
});
console.log(list);
}
toString() {
if (this.isEmpty) {
return '';
}
let str = `${this.list[this.head]}`;
for (let i = this.head + 1; i < this.tail; i++) {
str += `, ${this.list[i]}`;
}
return str;
}
}
const q = new Queue<number>(2);
q.enqueue(1);
q.enqueue(2);
q.print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment