|
5 | 5 | * implementation uses an array to store the queue. |
6 | 6 | */ |
7 | 7 |
|
8 | | -// Functions: enqueue, dequeue, peek, view, length |
9 | | - |
10 | | -const Queue = (function () { |
| 8 | +// Functions: enqueue, dequeue, peek, view, length, empty |
| 9 | +class Queue { |
11 | 10 | // constructor |
12 | | - function Queue () { |
| 11 | + constructor () { |
13 | 12 | // This is the array representation of the queue |
14 | 13 | this.queue = [] |
15 | 14 | } |
16 | 15 |
|
17 | 16 | // methods |
18 | 17 | // Add a value to the end of the queue |
19 | | - Queue.prototype.enqueue = function (item) { |
| 18 | + enqueue (item) { |
20 | 19 | this.queue.push(item) |
21 | 20 | } |
22 | 21 |
|
23 | 22 | // Removes the value at the front of the queue |
24 | | - Queue.prototype.dequeue = function () { |
25 | | - if (this.queue.length === 0) { |
| 23 | + dequeue () { |
| 24 | + if (this.empty()) { |
26 | 25 | throw new Error('Queue is Empty') |
27 | 26 | } |
28 | 27 |
|
29 | | - const result = this.queue[0] |
30 | | - this.queue.splice(0, 1) // remove the item at position 0 from the array |
31 | | - |
32 | | - return result |
| 28 | + return this.queue.shift() // remove the item at position 0 from the array and return it |
33 | 29 | } |
34 | 30 |
|
35 | 31 | // Return the length of the queue |
36 | | - Queue.prototype.length = function () { |
| 32 | + length () { |
37 | 33 | return this.queue.length |
38 | 34 | } |
39 | 35 |
|
40 | 36 | // Return the item at the front of the queue |
41 | | - Queue.prototype.peek = function () { |
| 37 | + peek () { |
| 38 | + if (this.empty()) { |
| 39 | + throw new Error('Queue is Empty') |
| 40 | + } |
| 41 | + |
42 | 42 | return this.queue[0] |
43 | 43 | } |
44 | 44 |
|
45 | 45 | // List all the items in the queue |
46 | | - Queue.prototype.view = function (output = value => console.log(value)) { |
| 46 | + view (output = value => console.log(value)) { |
47 | 47 | output(this.queue) |
48 | 48 | } |
49 | 49 |
|
50 | | - return Queue |
51 | | -}()) |
| 50 | + // Return Is queue empty ? |
| 51 | + empty () { |
| 52 | + return this.queue.length === 0 |
| 53 | + } |
| 54 | +} |
52 | 55 |
|
53 | 56 | export { Queue } |
0 commit comments