1
1
function PriorityQueue ( ) {
2
2
3
- this . items = [ ] ;
3
+ var items = [ ] ;
4
4
5
5
function QueueElement ( element , priority ) {
6
- this . element = element ;
7
- this . priority = priority ;
6
+ element = element ;
7
+ priority = priority ;
8
8
}
9
9
10
10
this . enqueue = function ( element , priority ) {
11
11
var queueElement = new QueueElement ( element , priority ) ;
12
12
13
- if ( this . isEmpty ( ) ) {
14
- this . items . push ( queueElement ) ;
13
+ if ( isEmpty ( ) ) {
14
+ items . push ( queueElement ) ;
15
15
} else {
16
- for ( var i = 0 ; i < this . items . length ; i ++ ) {
17
- if ( queueElement . priority < this . items [ i ] . priority ) {
18
- this . items . splice ( i , 0 , queueElement ) ;
16
+ var added = false ;
17
+ for ( var i = 0 ; i < items . length ; i ++ ) {
18
+ if ( queueElement . priority < items [ i ] . priority ) {
19
+ items . splice ( i , 0 , queueElement ) ;
20
+ added = true ;
19
21
break ;
20
22
}
21
23
}
24
+ if ( ! added ) {
25
+ items . push ( queueElement ) ;
26
+ }
22
27
}
23
28
} ;
24
29
25
30
this . dequeue = function ( ) {
26
- return this . items . shift ( ) ;
31
+ return items . shift ( ) ;
27
32
} ;
28
33
29
34
this . front = function ( ) {
30
- return this . items [ 0 ] ;
35
+ return items [ 0 ] ;
31
36
} ;
32
37
33
38
this . isEmpty = function ( ) {
34
- return this . items . length == 0 ;
39
+ return items . length == 0 ;
35
40
} ;
36
41
37
42
this . size = function ( ) {
38
- return this . items . length ;
43
+ return items . length ;
39
44
} ;
40
45
41
- this . print = function ( ) {
42
- for ( var i = 0 ; i < this . items . length ; i ++ ) {
43
- console . log ( this . items [ i ] . element + ' - ' + this . items [ i ] . priority ) ;
46
+ this . print = function ( ) {
47
+ for ( var i = 0 ; i < items . length ; i ++ ) {
48
+ console . log ( items [ i ] . element + ' - ' + items [ i ] . priority ) ;
44
49
}
45
50
} ;
46
51
}
@@ -49,5 +54,7 @@ var priorityQueue = new PriorityQueue();
49
54
priorityQueue . enqueue ( "John" , 2 ) ;
50
55
priorityQueue . enqueue ( "Jack" , 1 ) ;
51
56
priorityQueue . enqueue ( "Camila" , 1 ) ;
57
+ priorityQueue . enqueue ( "Maxwell" , 2 ) ;
58
+ priorityQueue . enqueue ( "Ana" , 3 ) ;
52
59
priorityQueue . print ( ) ;
53
60
0 commit comments