7
7
8
8
//Functions: enqueue, dequeue, peek, view, length
9
9
10
- var Queue = function ( ) {
10
+ var Queue = ( function ( ) {
11
11
12
- //This is the array representation of the queue
13
- this . queue = [ ] ;
12
+ // constructor
13
+ function Queue ( ) {
14
14
15
+ //This is the array representation of the queue
16
+ this . queue = [ ] ;
17
+
18
+ }
19
+
20
+ // methods
15
21
//Add a value to the end of the queue
16
- this . enqueue = function ( item ) {
22
+ Queue . prototype . enqueue = function ( item ) {
17
23
this . queue [ this . queue . length ] = item ;
18
- }
24
+ } ;
19
25
20
26
//Removes the value at the front of the queue
21
- this . dequeue = function ( ) {
27
+ Queue . prototype . dequeue = function ( ) {
22
28
if ( this . queue . length === 0 ) {
23
- return "Queue is Empty" ;
29
+ throw "Queue is Empty" ;
24
30
}
25
31
26
32
var result = this . queue [ 0 ] ;
27
33
this . queue . splice ( 0 , 1 ) ; //remove the item at position 0 from the array
28
34
29
35
return result ;
30
- }
36
+ } ;
31
37
32
38
//Return the length of the queue
33
- this . length = function ( ) {
39
+ Queue . prototype . length = function ( ) {
34
40
return this . queue . length ;
35
- }
41
+ } ;
36
42
37
43
//Return the item at the front of the queue
38
- this . peek = function ( ) {
44
+ Queue . prototype . peek = function ( ) {
39
45
return this . queue [ 0 ] ;
40
- }
46
+ } ;
41
47
42
48
//List all the items in the queue
43
- this . view = function ( ) {
49
+ Queue . prototype . view = function ( ) {
44
50
console . log ( this . queue ) ;
45
- }
46
- }
51
+ } ;
52
+
53
+ return Queue ;
54
+
55
+ } ( ) ) ;
47
56
48
57
//Implementation
49
58
var myQueue = new Queue ( ) ;
@@ -72,4 +81,4 @@ for (var i = 0; i < 5; i++) {
72
81
myQueue . view ( ) ;
73
82
}
74
83
75
- console . log ( myQueue . dequeue ( ) ) ;
84
+ // console.log(myQueue.dequeue()); // throws exception!
0 commit comments