( array: T[], compareFn: (item: T) => number, startIdx: number = 0, )
| 129 | return -1; |
| 130 | } |
| 131 | |
| 132 | startIdx = Math.max(0, Math.min(startIdx, len - 1)); |
| 133 | |
| 134 | const diff = compareFn(array[startIdx]); |
| 135 | if (diff === 0) { |
| 136 | return startIdx; |
| 137 | } |
| 138 | |
| 139 | let lo: number; |
| 140 | let hi: number; |
| 141 | |
| 142 | if (diff < 0) { |
| 143 | // Entry is "lower" than target — search forward. |
| 144 | let bound = 1; |
| 145 | while (startIdx + bound < len) { |
| 146 | const d = compareFn(array[startIdx + bound]); |
| 147 | if (d === 0) return startIdx + bound; |
| 148 | if (d > 0) break; |
| 149 | bound *= 2; |
| 150 | } |
| 151 | lo = startIdx + Math.floor(bound / 2) + 1; |
| 152 | hi = Math.min(startIdx + bound - 1, len - 1); |
| 153 | } else { |
| 154 | // Entry is "higher" than target — search backward. |
| 155 | let bound = 1; |
| 156 | while (startIdx - bound >= 0) { |
| 157 | const d = compareFn(array[startIdx - bound]); |
| 158 | if (d === 0) return startIdx - bound; |
| 159 | if (d < 0) break; |
| 160 | bound *= 2; |
| 161 | } |
| 162 | lo = Math.max(startIdx - bound + 1, 0); |
| 163 | hi = startIdx - Math.floor(bound / 2) - 1; |
| 164 | } |
| 165 | |
| 166 | return lo <= hi ? binarySearch(array, compareFn, lo, hi) : -1; |
| 167 | } |
| 168 | |
| 169 | /** |
| 170 | * Given an array, group the items by the given keySelector into a map. |
| 171 | */ |
| 172 | export function groupBy<T>(array: T[], keySelector: (item: T) => string): StringMap<T[]> { |
| 173 | const output: StringMap<T[]> = {}; |
| 174 | |
| 175 | for (const item of array) { |
| 176 | const key = keySelector(item); |
| 177 | let itemsForKey = output[key]; |
| 178 | if (!itemsForKey) { |
| 179 | itemsForKey = []; |
no test coverage detected