Skip to content

Instantly share code, notes, and snippets.

@tmgldn
Created April 11, 2020 19:46
Show Gist options
  • Select an option

  • Save tmgldn/142f2e0b2c1670812959e3588c4fa8a2 to your computer and use it in GitHub Desktop.

Select an option

Save tmgldn/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;
@tmgldn
Copy link
Author

tmgldn commented Sep 5, 2021

@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