( array: T[], compareFn: (item: T) => number, result?: Range, start?: number, end?: number, )
| 79 | result?: Range, |
| 80 | start?: number, |
| 81 | end?: number, |
| 82 | ): Range { |
| 83 | let lo = start ?? 0; |
| 84 | let hi = end ?? array.length - 1; |
| 85 | |
| 86 | // Iterate while start not meets end |
| 87 | while (lo <= hi) { |
| 88 | // Find the mid index |
| 89 | const mid = Math.floor((lo + hi) / 2); |
| 90 | |
| 91 | const diff = compareFn(array[mid]); |
| 92 | if (diff === 0) { |
| 93 | return { |
| 94 | min: mid, |
| 95 | max: mid, |
| 96 | }; |
| 97 | } else if (diff > 0) { |
| 98 | hi = mid - 1; |
| 99 | } else { |
| 100 | lo = mid + 1; |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | const min = Math.min(lo, hi); |
| 105 | const max = Math.max(lo, hi); |
| 106 | if (result) { |
| 107 | result.min = min; |
| 108 | result.max = max; |
| 109 | return result; |
| 110 | } else { |
| 111 | return { |
| 112 | min: min, |
| 113 | max: max, |
| 114 | }; |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | /** |
| 119 | * Exponential search from a start index within a sorted array. |
| 120 | * O(log d) where d is the distance from startIdx to the target. |
| 121 | * |
| 122 | * the compareFn should return >0 to indicate that the given item is "higher" |
| 123 | * than the searched index, <0 to indicate that the given item is "lower", |
| 124 | * 0 to indicate a perfect match. |
no test coverage detected