1
1
function PriorityQueue ( ) {
2
2
3
- var items = [ ] ;
3
+ let items = [ ] ;
4
4
5
- function QueueElement ( element , priority ) {
5
+ function QueueElement ( element , priority ) { // {1}
6
6
this . element = element ;
7
7
this . priority = priority ;
8
8
}
9
9
10
10
this . enqueue = function ( element , priority ) {
11
- var queueElement = new QueueElement ( element , priority ) ;
12
-
13
- if ( this . isEmpty ( ) ) {
14
- items . push ( queueElement ) ;
15
- } else {
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 ;
21
- break ;
22
- }
23
- }
24
- if ( ! added ) {
25
- items . push ( queueElement ) ;
11
+ let queueElement = new QueueElement ( element , priority ) ;
12
+
13
+ let added = false ;
14
+ for ( let i = 0 ; i < items . length ; i ++ ) {
15
+ if ( queueElement . priority < items [ i ] . priority ) { // {2}
16
+ items . splice ( i , 0 , queueElement ) ; // {3}
17
+ added = true ;
18
+ break ; // {4}
26
19
}
27
20
}
21
+ if ( ! added ) {
22
+ items . push ( queueElement ) ; //{5}
23
+ }
28
24
} ;
29
25
30
26
this . dequeue = function ( ) {
@@ -43,14 +39,14 @@ function PriorityQueue() {
43
39
return items . length ;
44
40
} ;
45
41
46
- this . print = function ( ) {
47
- for ( var i = 0 ; i < items . length ; i ++ ) {
48
- console . log ( items [ i ] . element + ' - ' + items [ i ] . priority ) ;
42
+ this . print = function ( ) {
43
+ for ( let i = 0 ; i < items . length ; i ++ ) {
44
+ console . log ( ` ${ items [ i ] . element } - ${ items [ i ] . priority } ` ) ;
49
45
}
50
46
} ;
51
47
}
52
48
53
- var priorityQueue = new PriorityQueue ( ) ;
49
+ let priorityQueue = new PriorityQueue ( ) ;
54
50
priorityQueue . enqueue ( "John" , 2 ) ;
55
51
priorityQueue . enqueue ( "Jack" , 1 ) ;
56
52
priorityQueue . enqueue ( "Camila" , 1 ) ;
0 commit comments