11function PriorityQueue ( ) {
22
3- this . items = [ ] ;
3+ var items = [ ] ;
44
55 function QueueElement ( element , priority ) {
6- this . element = element ;
7- this . priority = priority ;
6+ element = element ;
7+ priority = priority ;
88 }
99
1010 this . enqueue = function ( element , priority ) {
1111 var queueElement = new QueueElement ( element , priority ) ;
1212
13- if ( this . isEmpty ( ) ) {
14- this . items . push ( queueElement ) ;
13+ if ( isEmpty ( ) ) {
14+ items . push ( queueElement ) ;
1515 } 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 ;
1921 break ;
2022 }
2123 }
24+ if ( ! added ) {
25+ items . push ( queueElement ) ;
26+ }
2227 }
2328 } ;
2429
2530 this . dequeue = function ( ) {
26- return this . items . shift ( ) ;
31+ return items . shift ( ) ;
2732 } ;
2833
2934 this . front = function ( ) {
30- return this . items [ 0 ] ;
35+ return items [ 0 ] ;
3136 } ;
3237
3338 this . isEmpty = function ( ) {
34- return this . items . length == 0 ;
39+ return items . length == 0 ;
3540 } ;
3641
3742 this . size = function ( ) {
38- return this . items . length ;
43+ return items . length ;
3944 } ;
4045
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 ) ;
4449 }
4550 } ;
4651}
@@ -49,5 +54,7 @@ var priorityQueue = new PriorityQueue();
4954priorityQueue . enqueue ( "John" , 2 ) ;
5055priorityQueue . enqueue ( "Jack" , 1 ) ;
5156priorityQueue . enqueue ( "Camila" , 1 ) ;
57+ priorityQueue . enqueue ( "Maxwell" , 2 ) ;
58+ priorityQueue . enqueue ( "Ana" , 3 ) ;
5259priorityQueue . print ( ) ;
5360
0 commit comments