2017-09-28 10:52:12 -04:00
|
|
|
/* Queue
|
|
|
|
|
* A Queue is a data structure that allows you to add an element to the end of
|
|
|
|
|
* a list and remove the item at the front. A queue follows a "First In First Out"
|
|
|
|
|
* system, where the first item to enter the queue is the first to be removed. This
|
|
|
|
|
* implementation uses an array to store the queue.
|
|
|
|
|
*/
|
|
|
|
|
|
2020-05-03 09:05:12 +02:00
|
|
|
// Functions: enqueue, dequeue, peek, view, length
|
2017-09-28 10:52:12 -04:00
|
|
|
|
2020-10-31 12:03:11 +05:30
|
|
|
const Queue = (function () {
|
2018-03-30 16:04:27 +02:00
|
|
|
// constructor
|
2020-05-03 09:05:12 +02:00
|
|
|
function Queue () {
|
|
|
|
|
// This is the array representation of the queue
|
|
|
|
|
this.queue = []
|
2018-03-30 16:03:13 +02:00
|
|
|
}
|
2017-09-28 10:52:12 -04:00
|
|
|
|
2020-05-03 09:05:12 +02:00
|
|
|
// methods
|
|
|
|
|
// Add a value to the end of the queue
|
2018-03-30 16:03:13 +02:00
|
|
|
Queue.prototype.enqueue = function (item) {
|
2020-10-27 02:59:07 +06:00
|
|
|
this.queue.push(item)
|
2020-05-03 09:05:12 +02:00
|
|
|
}
|
2017-09-28 10:52:12 -04:00
|
|
|
|
2020-05-03 09:05:12 +02:00
|
|
|
// Removes the value at the front of the queue
|
2018-03-30 16:03:13 +02:00
|
|
|
Queue.prototype.dequeue = function () {
|
2017-10-01 20:24:25 -04:00
|
|
|
if (this.queue.length === 0) {
|
2020-05-03 21:26:52 -03:00
|
|
|
throw new Error('Queue is Empty')
|
2017-09-28 10:52:12 -04:00
|
|
|
}
|
|
|
|
|
|
2020-10-31 12:03:11 +05:30
|
|
|
const result = this.queue[0]
|
2020-05-03 09:05:12 +02:00
|
|
|
this.queue.splice(0, 1) // remove the item at position 0 from the array
|
2017-09-28 10:52:12 -04:00
|
|
|
|
2020-05-03 09:05:12 +02:00
|
|
|
return result
|
|
|
|
|
}
|
2017-09-28 10:52:12 -04:00
|
|
|
|
2020-05-03 09:05:12 +02:00
|
|
|
// Return the length of the queue
|
2018-03-30 16:03:13 +02:00
|
|
|
Queue.prototype.length = function () {
|
2020-05-03 09:05:12 +02:00
|
|
|
return this.queue.length
|
|
|
|
|
}
|
2017-09-28 10:52:12 -04:00
|
|
|
|
2020-05-03 09:05:12 +02:00
|
|
|
// Return the item at the front of the queue
|
2018-03-30 16:03:13 +02:00
|
|
|
Queue.prototype.peek = function () {
|
2020-05-03 09:05:12 +02:00
|
|
|
return this.queue[0]
|
|
|
|
|
}
|
2017-09-28 10:52:12 -04:00
|
|
|
|
2020-05-03 09:05:12 +02:00
|
|
|
// List all the items in the queue
|
2021-10-10 16:11:06 +02:00
|
|
|
Queue.prototype.view = function (output = value => console.log(value)) {
|
|
|
|
|
output(this.queue)
|
2020-05-03 09:05:12 +02:00
|
|
|
}
|
2018-03-30 16:03:13 +02:00
|
|
|
|
2020-05-03 09:05:12 +02:00
|
|
|
return Queue
|
|
|
|
|
}())
|
2017-09-28 10:52:12 -04:00
|
|
|
|
2021-10-10 16:11:06 +02:00
|
|
|
export { Queue }
|