Exercise: Queue and Stack
Queue and stack both are data structures used to handle a collection of data in
programming languages. In this section, we will implement the queue and stack using classes in
JavaScript as a way to practice using classes and getting to know them. What we are
implementing here is a matter of personal design as queue and stack can be designed more or
less differently but they have some common approaches that should be considered.
Queue
Queue follows the first-in-first-out principle, often referred to as FIFO. A queue enqueues
an item and dequeues it first, meaning that the first item that has been added to the queue will be
accessed first.
First, we need to define the Queue class in a file called [Link] with a constructor to define the
items array.
class Queue {
constructor() {
[Link] = []
}
}
Now we should implement a method to enqueuer the items:
class Queue {
constructor() {
[Link] = []
}
enqueue(item) {
[Link](item)
}
}
Now we need a method to dequeue, which means returning the first added item and then
removing it from the queue.
class Queue {
98