Queue in Javascript
A Queue is a linear structure that follows a particular order in which the operations are performed. The order is First In First Out (FIFO). It is similar to the ticket queue outside a cinema hall, where the first person entering the queue is the first person who gets the ticket.
Operations of Queue:
A queue is an object (an abstract data structure – ADT) that allows the following operations:
- Enqueue: Add an element to the end of the queue
- Dequeue: Remove an element from the front of the queue
- IsEmpty: Check if the queue is empty
- IsFull: Check if the queue is full
- top/Peek: Get the value of the front of the queue without removing it
Below is the implementation of Queue in javascript:
class Queue {
constructor() {
this.items = {}
this.frontIndex = 0
this.backIndex = 0
}
enqueue(item) {
this.items[this.backIndex] = item
this.backIndex++
return item + ' inserted'
}
dequeue() {
const item = this.items[this.frontIndex]
delete this.items[this.frontIndex]
this.frontIndex++
return item
}
peek() {
return this.items[this.frontIndex]
}
get printQueue() {
return this.items;
}
// isEmpty function
isEmpty() {
// return true if the queue is empty.
return this.items.length == 0;
}
}
const queue = new Queue()
console.log(queue.enqueue(7))
console.log(queue.enqueue(2))
console.log(queue.enqueue(6))
console.log(queue.enqueue(4))
console.log(queue.dequeue())
console.log(queue.peek())
var str = queue.printQueue;
console.log(str)
Output
7 inserted 2 inserted 6 inserted 4 inserted 7 2 { '1': 2, '2': 6, '3': 4 }
Learn Data Structures with Javascript | DSA using JavaScript Tutorial
JavaScript (JS) is the most popular lightweight, interpreted compiled programming language, and might be your first preference for Client-side as well as Server-side developments. But have you thought about using Javascript for DSA? Learning Data Structures and Algorithms can be difficult when combined with Javascript. For this reason, we have brought to you this detailed DSA tutorial on how to get started with Data Structures with Javascript from scratch.
Table of Content
- What is Data Structure?
- How to start learning Data Structures with Javascript?
- Learn about Complexities
- Learn Data Structures with JavaScript
- Array in javascript
- String in javascript
- Linked List in Javascript
- Stack in Javascript
- Queue in Javascript
- Tree in Javascript
- Priority Queue in Javascript
- Map in Javascript
- Set in Javascript
- Graph in Javascript
Contact Us