Tiktok tu
A simple implementation of the Queue data structure in JavaScript. This repository demonstrates how to create a queue class with essential methods and explains its functionality with practical examples.
A Queue is a data structure that follows the FIFO (First In, First Out) principle. The first element added to the queue is the first one to be removed. Think of it as a line at a coffee shop: the first person in line gets served first.
- Enqueue: Add an item to the queue.
- Dequeue: Remove and return the first item.
- Peek: View the first item without removing it.
- isEmpty: Check if the queue is empty.
- Size: Get the number of items in the queue.
Want to see a quick tutorial on how to build this? Check out this TikTok video:
https://www.tiktok.com/@jsmentoring/video/7461216459239247136
Hereβs the JavaScript implementation of the queue:
class Queue { constructor() { this.items = []; // Initialize an empty array } // Add an item to the queue enqueue(element) { this.items.push(element); } // Remove and return the front item dequeue() { if (this.isEmpty()) { return "Queue is empty!"; } return this.items.shift(); } // Check if the queue is empty isEmpty() { return this.items.length === 0; } // Peek at the front item without removing it peek() { if (this.isEmpty()) { return "Queue is empty!"; } return this.items[0]; } // Get the size of the queue size() { return this.items.length; } }
// Initialize the queue const queue = new Queue(); // Add items to the queue queue.enqueue("Task 1"); queue.enqueue("Task 2"); queue.enqueue("Task 3"); // Peek at the front item console.log(queue.peek()); // Output: Task 1 // Remove items from the queue console.log(queue.dequeue()); // Output: Task 1 console.log(queue.dequeue()); // Output: Task 2 // Check if the queue is empty console.log(queue.isEmpty()); // Output: false // Get the size of the queue console.log(queue.size()); // Output: 1
- Task Scheduling: Managing tasks in order of arrival.
- Print Queue: Handling print jobs in a printer.
- Breadth-First Search (BFS): Traversing graphs or trees.
- Customer Service Systems: Serving customers in the order they arrive.
- Clone the repository:
git clone https://github.com/your-username/queue-data-structure.git cd queue-data-structure - Open the file
queue.jsin your favorite code editor. - Run the file using Node.js:
node queue.js
Contributions are welcome! If you have suggestions or want to add new features, feel free to create a pull request.
This project is licensed under the MIT License.
- LinkedIn - Vitalii Semianchuk
- Telegram - @jsmentorfree - We do a lot of free teaching on this channel! Join us to learn and grow in web development.
- Tiktok - @jsmentoring Everyday new videos
- Youtube - @jsmentor-uk Mentor live streams
- Dev.to - fix2015 Javascript featured, live, experience