Created
August 3, 2024 08:18
-
-
Save gofer/4d2b49cfa2802a354af5510a545efb96 to your computer and use it in GitHub Desktop.
Queue (Ring Queue)
This file contains hidden or 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 QueueOverflow extends Error {} | |
class MyQueue { | |
constructor(capacity) { | |
this.array = []; | |
this.head = 0; | |
this.tail = 0; | |
this.capacity = capacity; | |
} | |
isEmpty() { | |
return this.head == this.tail && this.array[this.head] === undefined; | |
} | |
isFull() { | |
return this.head == this.tail && this.array[this.tail] !== undefined; | |
} | |
peek() { | |
return this.array[this.head]; | |
} | |
__nextHead() { | |
return (this.head + 1) % this.capacity; | |
} | |
__nextTail() { | |
return (this.tail + 1) % this.capacity; | |
} | |
enqueue(value) { | |
if (this.isFull()) { | |
throw new QueueOverflow(); | |
} | |
this.array[this.tail] = value; | |
this.tail = this.__nextTail(); | |
return this; | |
} | |
dequeue() { | |
if (this.isEmpty()) { | |
return undefined; | |
} | |
this.array[this.head] = undefined; | |
this.head = this.__nextHead(); | |
return this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment