Skip to content

Commit 5ec422e

Browse files
author
Christian Bender
committed
more objectoriented
1 parent b9d749a commit 5ec422e

File tree

1 file changed

+23
-16
lines changed

1 file changed

+23
-16
lines changed

Data Structures/Queue/Queue.js

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,43 +7,50 @@
77

88
//Functions: enqueue, dequeue, peek, view, length
99

10-
var Queue = function() {
10+
var Queue = (function () {
1111

12-
//This is the array representation of the queue
13-
this.queue = [];
12+
function Queue() {
13+
14+
//This is the array representation of the queue
15+
this.queue = [];
16+
17+
}
1418

1519
//Add a value to the end of the queue
16-
this.enqueue = function(item) {
20+
Queue.prototype.enqueue = function (item) {
1721
this.queue[this.queue.length] = item;
18-
}
22+
};
1923

2024
//Removes the value at the front of the queue
21-
this.dequeue = function() {
25+
Queue.prototype.dequeue = function () {
2226
if (this.queue.length === 0) {
23-
return "Queue is Empty";
27+
throw "Queue is Empty";
2428
}
2529

2630
var result = this.queue[0];
2731
this.queue.splice(0, 1); //remove the item at position 0 from the array
2832

2933
return result;
30-
}
34+
};
3135

3236
//Return the length of the queue
33-
this.length = function() {
37+
Queue.prototype.length = function () {
3438
return this.queue.length;
35-
}
39+
};
3640

3741
//Return the item at the front of the queue
38-
this.peek = function() {
42+
Queue.prototype.peek = function () {
3943
return this.queue[0];
40-
}
44+
};
4145

4246
//List all the items in the queue
43-
this.view = function() {
47+
Queue.prototype.view = function () {
4448
console.log(this.queue);
45-
}
46-
}
49+
};
50+
51+
return Queue;
52+
53+
}());
4754

4855
//Implementation
4956
var myQueue = new Queue();
@@ -72,4 +79,4 @@ for (var i = 0; i < 5; i++) {
7279
myQueue.view();
7380
}
7481

75-
console.log(myQueue.dequeue());
82+
//console.log(myQueue.dequeue());

0 commit comments

Comments
 (0)