Skip to content

Instantly share code, notes, and snippets.

@webstoreportal
Forked from tbjgolden/Queue.ts
Created June 14, 2021 22:44
Show Gist options
  • Save webstoreportal/425b0af3fa9394742098b44ed7b46335 to your computer and use it in GitHub Desktop.
Save webstoreportal/425b0af3fa9394742098b44ed7b46335 to your computer and use it in GitHub Desktop.
Fast implementation of a queue in TypeScript/JavaScript
class Queue {
private readonly queue: any[];
private start: number;
private end: number;
constructor(array: any[] = []) {
this.queue = array;
// pointers
this.start = 0;
this.end = array.length;
}
isEmpty() {
return this.end === this.start;
}
dequeue() {
if (this.isEmpty()) {
throw new Error("Queue is empty.");
} else {
return this.queue[this.start++];
}
}
enqueue(value: any) {
this.queue.push(value);
this.end += 1;
}
toString() {
return `Queue (${this.end - this.start})`;
}
[Symbol.iterator]() {
let index = this.start;
return {
next: () =>
index < this.end
? {
value: this.queue[index++]
}
: { done: true }
};
}
}
export default Queue;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment