Skip to content

Instantly share code, notes, and snippets.

@gofer
Created August 3, 2024 08:18
Show Gist options
  • Save gofer/4d2b49cfa2802a354af5510a545efb96 to your computer and use it in GitHub Desktop.
Save gofer/4d2b49cfa2802a354af5510a545efb96 to your computer and use it in GitHub Desktop.
Queue (Ring Queue)
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