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+ // constructor
13+ function Queue ( ) {
1414
15+ //This is the array representation of the queue
16+ this . queue = [ ] ;
17+
18+ }
19+
20+ // methods
1521 //Add a value to the end of the queue
16- this . enqueue = function ( item ) {
22+ Queue . prototype . enqueue = function ( item ) {
1723 this . queue [ this . queue . length ] = item ;
18- }
24+ } ;
1925
2026 //Removes the value at the front of the queue
21- this . dequeue = function ( ) {
27+ Queue . prototype . dequeue = function ( ) {
2228 if ( this . queue . length === 0 ) {
23- return "Queue is Empty" ;
29+ throw "Queue is Empty" ;
2430 }
2531
2632 var result = this . queue [ 0 ] ;
2733 this . queue . splice ( 0 , 1 ) ; //remove the item at position 0 from the array
2834
2935 return result ;
30- }
36+ } ;
3137
3238 //Return the length of the queue
33- this . length = function ( ) {
39+ Queue . prototype . length = function ( ) {
3440 return this . queue . length ;
35- }
41+ } ;
3642
3743 //Return the item at the front of the queue
38- this . peek = function ( ) {
44+ Queue . prototype . peek = function ( ) {
3945 return this . queue [ 0 ] ;
40- }
46+ } ;
4147
4248 //List all the items in the queue
43- this . view = function ( ) {
49+ Queue . prototype . view = function ( ) {
4450 console . log ( this . queue ) ;
45- }
46- }
51+ } ;
52+
53+ return Queue ;
54+
55+ } ( ) ) ;
4756
4857//Implementation
4958var myQueue = new Queue ( ) ;
@@ -72,4 +81,4 @@ for (var i = 0; i < 5; i++) {
7281 myQueue . view ( ) ;
7382}
7483
75- console . log ( myQueue . dequeue ( ) ) ;
84+ // console.log(myQueue.dequeue()); // throws exception!
0 commit comments