(
location: Position,
items: T[],
compare: (
location: Position,
items: T[],
index: number,
) => {index: number | null, direction: number},
)
| 85 | } |
| 86 | |
| 87 | function binSearch<T>( |
| 88 | location: Position, |
| 89 | items: T[], |
| 90 | compare: ( |
| 91 | location: Position, |
| 92 | items: T[], |
| 93 | index: number, |
| 94 | ) => {index: number | null, direction: number}, |
| 95 | ): T | null { |
| 96 | let count = items.length; |
| 97 | let index = 0; |
| 98 | let firstElementIndex = 0; |
| 99 | let step; |
| 100 | |
| 101 | while (count > 0) { |
| 102 | index = firstElementIndex; |
| 103 | step = Math.floor(count / 2); |
| 104 | index += step; |
| 105 | |
| 106 | const comparison = compare(location, items, index); |
| 107 | if (comparison.direction === 0) { |
| 108 | if (comparison.index == null) { |
| 109 | throw new Error('Expected an index when matching element is found.'); |
| 110 | } |
| 111 | firstElementIndex = comparison.index; |
| 112 | break; |
| 113 | } |
| 114 | |
| 115 | if (comparison.direction > 0) { |
| 116 | index++; |
| 117 | firstElementIndex = index; |
| 118 | count -= step + 1; |
| 119 | } else { |
| 120 | count = step; |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | return firstElementIndex != null ? items[firstElementIndex] : null; |
| 125 | } |
| 126 | |
| 127 | /** |
| 128 | * Compares the target line location to the current location |
no test coverage detected