Queue AN ordered group of items following a first-in, first-out (FIFO) principle
Here is the queue data structure that I encapsulated as I learned about queues
class Queue {
constructor() {
this.count = 0
this.item = {}
this.first = 0
}
enqueue(e) {
this.item[this.count] = e
this.count++
}
size() {
return this.count - this.first
}
isEmpty() {
return this.count - this.first === 0
}
dequeue() {
if(this.isEmpty()) {
return undefined
}else {
let res = this.item[this.first]
delete this.item[this.first]
this.first++
return res
}
}
toString() {
if(this.isEmpty()) {
return ""
}else {
let res = ""
for(let key in this.item) {
res += this.item[key]
}
return res
}
}
}
let q = new Queue()
q.enqueue('1')
q.enqueue('2')
q.enqueue('3')
q.enqueue('4')
console.log(q);
console.log(q.dequeue());
console.log(q.toString());
Copy the code
This simply encapsulates a queue data structure. I’m using the object method to hold the queue data, or I can use an array to encapsulate the queue data. Reference Book: Learning JacaScript Data Structures and Algorithms (3rd edition)