A queue is a simple that allows elements to be inserted from one end, called the rear (also called tail), and deleted from the other end, called the front (also called head). data structure This behavior is called . FIFO (First in First Out) So, a queue is a linear data structure. A very important concept is that a queue deletes only the added element. oldest The person that is removed was the first in the queue Applications Queues are used whenever we need to manage objects in order starting with the first one in. Scenarios include printing documents on a printer, call center systems answering people on hold people, and so on. Creation A queue can be implemented using an or a array linked list. So, in JavaScript doing a is very simple because we can take arrays methods, like and Queue unshift pop. Remember : Adds a element to the beginning of the array. Deletes the last element of the array. unshift pop Implementation So the first thing that we are going to do is create a Queue constructor function with a empty array inside. function Queue() {this.data = [];} Remember that we use the keyword there because we need to pointer the object that we create. this Methods The main methods will be and add remove: Queue.prototype.add = function(record) {this.data.unshift(record);} Queue.prototype.remove = function() {this.data.pop();} And we are going to add 3 methods more: Queue.prototype.first = function() {return this.data[0];} Queue.prototype.last = function() {return this.data[this.data.length - 1];} Queue.prototype.size = function() {return this.data.length;} So, let’s see what we get: const q = new Queue():q.add(1);q.add(2);q.add(3);console.log(q); So, the oldest one is the element with the value of 1 because we added it first. If you don’t believe me, you can use our method to see it: last console.log(q.first()); console.log(q.last()); // -> 3 // -> 1 So if we use the remove method the element that will be deleted is the oldest so the 1 is out. q.remove();console.log(q); And we have the last method call size console.log(q.size())// -> 2 Return ‘ after we delete the last element. ‘2’’ ; Complete Code: https://github.com/germancutraro/Queue-Data-Structure You have my Github if you wanna follow me, i will appreciate a lot! Thanks to a fantastic app! SoloLearn ◾ ◾ Great courses to learn Data Structures and Algorithms: Learning Data Structures in JavaScript from Scratch The Coding Interview Bootcamp: Algorithms + Data Structures Thank you 😊
Share Your Thoughts