Hey friends ๐
Even though Iโm a little late this week ๐ข, letโs keep our DSA series alive!๐ Like I indicated last week, today we're learning about Queues, a very common and beginner-friendly data structure.
A queue works just like a line at the bus stop ๐:
- Enqueue โ add a person to the back of the line
- Dequeue โ let the person at the front leave
- Peek โ check whoโs at the front without removing them
This is called FIFO (First In, First Out).
Building a Simple Queue in JavaScript
class Queue {
constructor() {
this.items = [];
}
enqueue(element) {
this.items.push(element);
}
dequeue() {
return this.items.shift();
}
peek() {
return this.items[0];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
}
// Example usage:
const queue = new Queue();
queue.enqueue("Alice");
queue.enqueue("Bob");
console.log(queue.peek()); // Alice
queue.dequeue();
console.log(queue.peek()); // Bob
๐ฎ Try It Yourself
๐ Live Queue Playground on CodePen
๐๐ฝโโ๏ธ Over to You!
Try expanding this queue:
- Add a Clear Queue button.
- Show the size of the queue.
- Animate items sliding when theyโre added or removed.
Let me know if you do the challenge! I'd like to see yours! Connect with me on GitHub
Was this tutorial helpful? Got questions? Or any insight to help me write better tutorials? Let me know in the ๐ฌ!
Thatโs it for todayโs midweek mini tutorial!
Iโm keeping things light, fun and useful; one small project at a time.
If you enjoyed this, leave a ๐ฌ or ๐งก to let me know.
And if youโve got an idea for something you'd like me to try out next Wednesday, drop it in the comments. ๐
Follow me to see more straight-forward and short tutorials like this :)
If you are curious about what I do, check out my Portfolio
:-)
Web trails
You can also find me here on LinkedIn
or here X (Twitter)
โ๐พ Iโm documenting my learning loudly every Wednesday. Follow along if you're learning JavaScript too!
Letโs keep learning together!
See you next Wednesday, hopefully, not Friday๐ ๐
Top comments (0)