-
-
Save webstoreportal/425b0af3fa9394742098b44ed7b46335 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment