Created
July 13, 2021 14:24
-
-
Save davidkayce/999d0b55310184b7b35461ea8f0d5c53 to your computer and use it in GitHub Desktop.
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
// Here we'd do a basic queue | |
export default class Queue { | |
private queue = []; | |
private offset = 0; | |
constructor(array = []) { | |
// Init the queue using the contents of the array | |
for (const item of array) { | |
this.enqueue(item); | |
} | |
} | |
/** | |
* @returns {number} the length of the queue. | |
*/ | |
public getLength(): number { | |
return (this.queue.length - this.offset); | |
} | |
/** | |
* @returns {boolean} true if the queue is empty, and false otherwise. | |
*/ | |
public isEmpty(): boolean { | |
return (this.queue.length === 0); | |
} | |
/** | |
* Enqueues the specified item. | |
* | |
* @param item - the item to enqueue | |
*/ | |
public enqueue(item) { | |
this.queue.push(item); | |
} | |
/** | |
* Dequeues an item and returns it. If the queue is empty, the value | |
* {@code null} is returned. | |
* | |
* @returns {any} | |
*/ | |
public dequeue(): any { | |
// if the queue is empty, return immediately | |
if (this.queue.length === 0) { | |
return null; | |
} | |
// store the item at the front of the queue | |
const item = this.queue[this.offset]; | |
// increment the offset and remove the free space if necessary | |
if (++this.offset * 2 >= this.queue.length) { | |
this.queue = this.queue.slice(this.offset); | |
this.offset = 0; | |
} | |
// return the dequeued item | |
return item; | |
}; | |
/** | |
* Returns the item at the front of the queue (without dequeuing it). | |
* If the queue is empty then {@code null} is returned. | |
* | |
* @returns {any} | |
*/ | |
public peek(): any { | |
return (this.queue.length > 0 ? this.queue[this.offset] : null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment