Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export class Queue<T> {
- /**
- * The elements in the queue
- */
- private elements: T[] = []
- /**
- * The head (index) of the queue.
- * For performance, this is not always zero, as would be expected.
- */
- private head = 0
- /**
- *
- */
- get length(): number {
- return this.elements.length - this.head
- };
- empty(): boolean {
- return this.elements.length === 0
- };
- put(element: T): void {
- this.elements.push(element)
- };
- get(): T {
- if (0 !== this.elements.length) {
- const c = this.elements[this.head]
- this.head++
- // If over half of the elements towards the front of the queue are no longer needed,
- // re-allocated the elements.
- if (2 * this.head >= this.elements.length) {
- this.elements = this.elements.slice(this.head)
- this.head = 0
- }
- return c
- }
- else {
- throw new Error("")
- }
- }
- peek(): T | undefined {
- return this.elements.length > 0 ? this.elements[this.head] : void 0
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement