🏛️ Data Structures

Queue

Description:

The queues is a data structure for list that follows the First In - First Out (FIFO) rule. The first element that enter the list, or the queue, is the first elements that is going to get out of the list.

You can see this as a supermarket line, the person that stand in line first is the person that is going to pay first. If 3 people enters the queue, the last person that entered the queue is going to be the last person to pay.

Implementation:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // Define a new queue. const queue = () => { // Define the data of the queue. let data: any[] = []; return { // Add elements to the end of the queue. push: (element: any) => { data = [...data, element]; }, // Get the first element to enter the queue. pop: (): any => { const elementToPop = data[0]; data = data.slice(1, data.length); return elementToPop; }, // Get the element that is in the first position of the queue. first: (): any => { return data[0]; }, // Get all the elments of the queque. list: (): any[] => { return data; } } };

Testing it

So, we are going to test in console to see if it is working. We are going to run the following:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 // Creates a new queue console.log('** Creates a new queue.'); const newQueue = queue(); // Add a elements to the queue. console.log('** Push elements to the queue.'); newQueue.push({item: "A"}); // Queue data after pushing. console.log('** Queue elements: ', newQueue.list().map(element => element.item).join(',')); newQueue.push({item: "B"}); // Queue data after pushing. console.log('** Queue elements: ', newQueue.list().map(element => element.item).join(',')); newQueue.push({item: "C"}); // Queue data after pushing. console.log('** Queue elements: ', newQueue.list().map(element => element.item).join(',')); newQueue.push({item: "D"}); // Queue data after pushing. console.log('** Queue elements: ', newQueue.list().map(element => element.item).join(',')); // Get the first element console.log('** Pop the first element.'); const firstElement = newQueue.pop(); console.log('firstElement: ', firstElement.item); // Queue data after pop. console.log('** Queue elements: ', newQueue.list().map(element => element.item).join(',')); // Add that element back to the queue. console.log('** Add that element back to the queue.'); newQueue.push(firstElement); // Final queue. console.log('** Final queue elements: ', newQueue.list().map(element => element.item).join(','));

You should see something like the following in the console:

0 1 2 3 4 5 6 7 8 9 10 11 ** Creates a new queue. ** Push elements to the queue. ** Queue elements: A ** Queue elements: A,B ** Queue elements: A,B,C ** Queue elements: A,B,C,D ** Pop the first element. firstElement: A ** Queue elements: B,C,D ** Add that element back to the queue. ** Final queue elements: B,C,D,A
🏛️ 🧮 📝 ⚛️ 🏠