Created
April 11, 2020 19:46
-
-
Save tbjgolden/142f2e0b2c1670812959e3588c4fa8a2 to your computer and use it in GitHub Desktop.
Fast implementation of a queue in TypeScript/JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
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
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. 👍