Skip to content

Instantly share code, notes, and snippets.

@tbjgolden
Created April 11, 2020 19:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tbjgolden/142f2e0b2c1670812959e3588c4fa8a2 to your computer and use it in GitHub Desktop.
Save tbjgolden/142f2e0b2c1670812959e3588c4fa8a2 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;
@lesterfernandez
Copy link

It has great time complexity but at the sacrifice of space complexity after many enqueues and dequeues. This is a nice and simple implementation, thanks for sharing. 👍

@tbjgolden
Copy link
Author

@lesterfernandez

Yeah - option could be to use a plain object with integer property keys instead of an array

Then you can delete the key when it is out of bounds which solves the memory issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment