mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 09:28:26 +08:00
more objectoriented
This commit is contained in:
@ -7,43 +7,50 @@
|
|||||||
|
|
||||||
//Functions: enqueue, dequeue, peek, view, length
|
//Functions: enqueue, dequeue, peek, view, length
|
||||||
|
|
||||||
var Queue = function() {
|
var Queue = (function () {
|
||||||
|
|
||||||
//This is the array representation of the queue
|
function Queue() {
|
||||||
this.queue = [];
|
|
||||||
|
//This is the array representation of the queue
|
||||||
|
this.queue = [];
|
||||||
|
|
||||||
//Add a value to the end of the queue
|
|
||||||
this.enqueue = function(item) {
|
|
||||||
this.queue[this.queue.length] = item;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//Add a value to the end of the queue
|
||||||
|
Queue.prototype.enqueue = function (item) {
|
||||||
|
this.queue[this.queue.length] = item;
|
||||||
|
};
|
||||||
|
|
||||||
//Removes the value at the front of the queue
|
//Removes the value at the front of the queue
|
||||||
this.dequeue = function() {
|
Queue.prototype.dequeue = function () {
|
||||||
if (this.queue.length === 0) {
|
if (this.queue.length === 0) {
|
||||||
return "Queue is Empty";
|
throw "Queue is Empty";
|
||||||
}
|
}
|
||||||
|
|
||||||
var result = this.queue[0];
|
var result = this.queue[0];
|
||||||
this.queue.splice(0, 1); //remove the item at position 0 from the array
|
this.queue.splice(0, 1); //remove the item at position 0 from the array
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
};
|
||||||
|
|
||||||
//Return the length of the queue
|
//Return the length of the queue
|
||||||
this.length = function() {
|
Queue.prototype.length = function () {
|
||||||
return this.queue.length;
|
return this.queue.length;
|
||||||
}
|
};
|
||||||
|
|
||||||
//Return the item at the front of the queue
|
//Return the item at the front of the queue
|
||||||
this.peek = function() {
|
Queue.prototype.peek = function () {
|
||||||
return this.queue[0];
|
return this.queue[0];
|
||||||
}
|
};
|
||||||
|
|
||||||
//List all the items in the queue
|
//List all the items in the queue
|
||||||
this.view = function() {
|
Queue.prototype.view = function () {
|
||||||
console.log(this.queue);
|
console.log(this.queue);
|
||||||
}
|
};
|
||||||
}
|
|
||||||
|
return Queue;
|
||||||
|
|
||||||
|
}());
|
||||||
|
|
||||||
//Implementation
|
//Implementation
|
||||||
var myQueue = new Queue();
|
var myQueue = new Queue();
|
||||||
@ -72,4 +79,4 @@ for (var i = 0; i < 5; i++) {
|
|||||||
myQueue.view();
|
myQueue.view();
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(myQueue.dequeue());
|
//console.log(myQueue.dequeue());
|
Reference in New Issue
Block a user