|
| 1 | + |
| 2 | + |
| 3 | +Like stacks, queues are a collection of elements. But unlike stacks, queues follow the FIFO (First-In First-Out) principle. |
| 4 | +Elements added to a queue are pushed to the tail, or the end, of the queue, and only the element at the front of the queue is allowed to be removed. |
| 5 | + |
| 6 | +We could use an array to represent a queue, but just like stacks, we want to limit the amount of control we have over our queues. |
| 7 | + |
| 8 | +The two main methods of a queue class is the enqueue and the dequeue method. |
| 9 | +The enqueue method pushes an element to the tail of the queue, and the dequeue method removes and returns the element at the front of the queue. Other useful methods are the front, size, and isEmpty methods. |
| 10 | + |
| 11 | +Write an `enqueue` method that pushes an element to the tail of the queue, |
| 12 | +a `dequeue` method that removes and returns the front element, |
| 13 | +a `front` method that lets us see the front element, |
| 14 | +a `size` method that shows the length, and an `isEmpty` method to check if the queue is empty. |
| 15 | + |
| 16 | +```js |
| 17 | +function Queue() { |
| 18 | + var collection = []; |
| 19 | + this.print = function() { |
| 20 | + console.log(collection); |
| 21 | + }; |
| 22 | + this.enqueue = function(el) { |
| 23 | + collection.push(el); |
| 24 | + }; |
| 25 | + |
| 26 | + this.dequeue = function() { |
| 27 | + return collection.shift() |
| 28 | + }; |
| 29 | + |
| 30 | + this.front = function() { |
| 31 | + return collection[0]; |
| 32 | + }; |
| 33 | + |
| 34 | + this.size = function() { |
| 35 | + return collection.length; |
| 36 | + }; |
| 37 | + |
| 38 | + this.isEmpty = function() { |
| 39 | + return (this.size == 0); |
| 40 | + }; |
| 41 | +} |
0 commit comments