Created
February 19, 2024 02:55
-
-
Save tdubs42/f70e10780c46619729b7017178192960 to your computer and use it in GitHub Desktop.
Queue Class - 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
const LinkedList = require("./LinkedList"); | |
class Queue { | |
constructor(maxSize = Infinity) { | |
this.queue = new LinkedList(); | |
this.maxSize = maxSize; | |
this.size = 0; | |
} | |
isEmpty() { | |
return this.size === 0; | |
} | |
hasRoom() { | |
return this.size < this.maxSize; | |
} | |
enqueue(data) { | |
if (this.hasRoom()) { | |
this.queue.addToTail(data); | |
this.size++; | |
} else { | |
throw new Error("Queue is full!"); | |
} | |
} | |
dequeue() { | |
if (!this.isEmpty()) { | |
const data = this.queue.removeHead(); | |
this.size--; | |
return data; | |
} else { | |
throw new Error("Queue is empty!"); | |
} | |
} | |
} | |
module.exports = Queue; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment