Skip to content

Instantly share code, notes, and snippets.

@fazeelanizam13
Created May 25, 2022 19:15
Show Gist options
  • Save fazeelanizam13/eddcdd0162e694801ced7f5f5432e869 to your computer and use it in GitHub Desktop.
Save fazeelanizam13/eddcdd0162e694801ced7f5f5432e869 to your computer and use it in GitHub Desktop.
Implementation of the queue data structure in JavaScript
class Item {
// stores given value and points to nothing
constructor (value) {
this.value = value
this.next = null
}
}
class Queue {
// initial size is 0 and initially just has two reference items that store nothing and point to nothing
constructor () {
this.size = 0
this.front = this.rear = new Item(null)
}
// helper function to test
// prints all items in queue in console
printItems = () => {
let item = this.front
if (item.next) {
while (item.next !== null) {
item = item.next
console.log(item.value)
}
} else console.log('Queue empty')
}
enqueue = value => {
// create new node
let item = new Item(value)
// make rear item point to new item
this.rear.next = item
// new item's point to null anyway so don't need this step
// item.next = null
// assign new item as new rear item
this.rear = item
this.size++
}
dequeue = () => {
// if no item, return
if (this.front.next === null) {
console.log("Queue empty.")
return null
}
// assign first item to temp
let temp = this.front.next
// connect front to second item
this.front.next = temp.next
// disconnect previous first item from queue
temp.next = null
this.size--
return temp.value
}
queueFront = () => {
// if there's a first item
if (this.front.next) {
let firstItem = this.front.next
return firstItem.value
} else return null
}
isEmpty = () => {
if (!this.front.next) return true
else return false
}
queueSize = () => {
return this.size
}
}
// tests
// const queue = new Queue()
// queue.printItems()
// console.log('size', queue.queueSize())
// queue.enqueue(7)
// queue.enqueue(8)
// queue.enqueue(5)
// queue.printItems()
// console.log('front', queue.queueFront())
// console.log('size', queue.queueSize())
// const removed = queue.dequeue()
// console.log('removed', removed)
// queue.printItems()
// console.log('empty', queue.isEmpty())
// queue.dequeue()
// queue.printItems()
// console.log('empty', queue.isEmpty())
// console.log('front', queue.queueFront())
// queue.dequeue()
// console.log('empty', queue.isEmpty())
// console.log('top', queue.queueFront())
// console.log('size', queue.queueSize())
// console.log('removed', queue.dequeue())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment