9
9
10
10
var Queue = function ( ) {
11
11
12
- //This keeps track of where the end of the queue is
13
- this . back = 0 ;
14
12
//This is the array representation of the queue
15
- this . queue = { } ;
13
+ this . queue = [ ] ;
16
14
17
15
//Add a value to the end of the queue
18
16
this . enqueue = function ( item ) {
19
- this . queue [ this . back ] = item ;
20
- this . back ++ ;
17
+ this . queue [ this . queue . length ] = item ;
21
18
}
22
19
23
20
//Removes the value at the front of the queue
24
21
this . dequeue = function ( ) {
25
- if ( this . back === 0 ) {
22
+ if ( this . queue . length === 0 ) {
26
23
return "Queue is Empty" ;
27
24
}
28
25
29
- var result = this . queue [ this . front ] ;
30
- delete this . queue [ this . front ] ;
31
-
32
- //Shift all the other items forward
33
- for ( var i = 1 ; i < this . back ; i ++ ) {
34
- this . queue [ i - 1 ] = this . queue [ i ] ;
35
- }
36
-
37
- //clean up the leftover duplicated value at the back of the queue
38
- delete this . queue [ this . back ] ;
39
- this . back -- ;
26
+ var result = this . queue [ 0 ] ;
27
+ this . queue . splice ( 0 , 1 ) ; //remove the item at position 0 from the array
40
28
41
29
return result ;
42
30
}
43
31
44
32
//Return the length of the queue
45
33
this . length = function ( ) {
46
- return this . back ;
34
+ return this . queue . length ;
47
35
}
48
36
49
37
//Return the item at the front of the queue
@@ -53,17 +41,7 @@ var Queue = function() {
53
41
54
42
//List all the items in the queue
55
43
this . view = function ( ) {
56
- var str = "{"
57
- //construct a single string to represent the items in the queue
58
- for ( var i = 0 ; i < this . back ; i ++ ) {
59
- str += this . queue [ i ] ;
60
- if ( i !== this . back - 1 ) {
61
- str += ", " ;
62
- }
63
- }
64
- str += "}" ;
65
-
66
- console . log ( str ) ;
44
+ console . log ( this . queue ) ;
67
45
}
68
46
}
69
47
0 commit comments