Skip to content

Instantly share code, notes, and snippets.

@nixjs
Created May 6, 2024 06:41
Show Gist options
  • Save nixjs/1961dbf7ac17f5696eab2f420dd88753 to your computer and use it in GitHub Desktop.
Save nixjs/1961dbf7ac17f5696eab2f420dd88753 to your computer and use it in GitHub Desktop.
class Queue<T = any> {
items: T[] = []
// Implementing various methods of javascript queue:
// 1. adding element to the queue
enqueue(item: T) {
this.items.push(item)
}
// 2. removing element from the queue
dequeue() {
// checking if the queue is empty or not before removing it!
if (this.isEmpty()) {
console.warn('[Queue] Queue is empty: underflow')
return undefined
}
return this.items.shift()
}
// 3. returning the Front element of
front() {
// checking if the queue is empty or not!
if (this.isEmpty()) {
console.warn('[Queue] Queue is empty')
return undefined
}
return this.items[0]
}
// 4. returning true if the queue is empty.
isEmpty() {
return this.items.length === 0
}
// 5. printing the queue.
printQueue() {
let queue = ''
for (let i = 0; i < this.items.length; i += 1) {
queue += this.items[i] + ' '
}
return queue
}
// 6. getting the size of the queue.
size() {
return this.items.length
}
// 6. getting the size of the queue.
clear() {
this.items = []
}
}
export default Queue
// // creating object of the Queue class:
// const queue = new Queue()
// // Adding elements to the queue
// queue.enqueue(1)
// queue.enqueue(2)
// queue.enqueue(3)
// queue.enqueue(4)
// queue.enqueue(5)
// // printing the current queue:
// console.log('the current queue is: ', queue.printQueue())
// // printing the top element of the queue.
// const topElement = queue.front()
// console.log('The top element of the queue is: ', topElement)
// // printing the size of the queue.
// console.log('The size of the queue is: ', queue.size())
// // removing elements form queue:
// let removedElement = queue.dequeue()
// console.log('Removed element is: ', removedElement)
// removedElement = queue.dequeue()
// console.log('Removed element is: ', removedElement)
// // printing the current queue:
// console.log('The current queue is: ', queue.printQueue())
// // printing the top element of the queue.
// console.log('The top element of the queue is: ', queue.front())
// // printing the size of the queue.
// console.log('The size of the queue is: ', queue.size())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment