( array: Array<T>, value: T, comparator: (a: T, b: T) => number, )
| 58 | } |
| 59 | |
| 60 | export function binarySearch<T>( |
| 61 | array: Array<T>, |
| 62 | value: T, |
| 63 | comparator: (a: T, b: T) => number, |
| 64 | ): number { |
| 65 | let low = 0 |
| 66 | let high = array.length |
| 67 | while (low < high) { |
| 68 | const mid = Math.floor((low + high) / 2) |
| 69 | const comparison = comparator(array[mid]!, value) |
| 70 | if (comparison < 0) { |
| 71 | low = mid + 1 |
| 72 | } else if (comparison > 0) { |
| 73 | high = mid |
| 74 | } else { |
| 75 | return mid |
| 76 | } |
| 77 | } |
| 78 | return low |
| 79 | } |
| 80 | |
| 81 | /** |
| 82 | * Utility for generating unique IDs for objects and values. |
no test coverage detected