@@ -28,7 +28,7 @@ export class SortedList<T> {
28
28
this . _array . push ( value ) ;
29
29
return ;
30
30
}
31
- i = this . _search ( this . _getKey ( value ) , 0 , this . _array . length - 1 ) ;
31
+ i = this . _search ( this . _getKey ( value ) ) ;
32
32
this . _array . splice ( i , 0 , value ) ;
33
33
}
34
34
@@ -40,7 +40,7 @@ export class SortedList<T> {
40
40
if ( key === undefined ) {
41
41
return false ;
42
42
}
43
- i = this . _search ( key , 0 , this . _array . length - 1 ) ;
43
+ i = this . _search ( key ) ;
44
44
if ( i === - 1 ) {
45
45
return false ;
46
46
}
@@ -60,7 +60,7 @@ export class SortedList<T> {
60
60
if ( this . _array . length === 0 ) {
61
61
return ;
62
62
}
63
- i = this . _search ( key , 0 , this . _array . length - 1 ) ;
63
+ i = this . _search ( key ) ;
64
64
if ( i < 0 || i >= this . _array . length ) {
65
65
return ;
66
66
}
@@ -76,7 +76,7 @@ export class SortedList<T> {
76
76
if ( this . _array . length === 0 ) {
77
77
return ;
78
78
}
79
- i = this . _search ( key , 0 , this . _array . length - 1 ) ;
79
+ i = this . _search ( key ) ;
80
80
if ( i < 0 || i >= this . _array . length ) {
81
81
return ;
82
82
}
@@ -92,23 +92,26 @@ export class SortedList<T> {
92
92
return this . _array . values ( ) ;
93
93
}
94
94
95
- private _search ( key : number , min : number , max : number ) : number {
96
- if ( max < min ) {
97
- return min ;
98
- }
99
- let mid = Math . floor ( ( min + max ) / 2 ) ;
100
- const midKey = this . _getKey ( this . _array [ mid ] ) ;
101
- if ( midKey > key ) {
102
- return this . _search ( key , min , mid - 1 ) ;
103
- }
104
- if ( midKey < key ) {
105
- return this . _search ( key , mid + 1 , max ) ;
106
- }
107
- // Value found! Since keys can be duplicates, move the result index back to the lowest index
108
- // that matches the key.
109
- while ( mid > 0 && this . _getKey ( this . _array [ mid - 1 ] ) === key ) {
110
- mid -- ;
95
+ private _search ( key : number ) : number {
96
+ let min = 0 ;
97
+ let max = this . _array . length - 1 ;
98
+ while ( max >= min ) {
99
+ let mid = ( min + max ) >> 1 ;
100
+ const midKey = this . _getKey ( this . _array [ mid ] ) ;
101
+ if ( midKey > key ) {
102
+ max = mid - 1 ;
103
+ } else if ( midKey < key ) {
104
+ min = mid + 1 ;
105
+ } else {
106
+ // key in list, walk to lowest duplicate
107
+ while ( mid > 0 && this . _getKey ( this . _array [ mid - 1 ] ) === key ) {
108
+ mid -- ;
109
+ }
110
+ return mid ;
111
+ }
111
112
}
112
- return mid ;
113
+ // key not in list
114
+ // still return closest min (also used as insert position)
115
+ return min ;
113
116
}
114
117
}
0 commit comments