Skip to content

Commit 3955435

Browse files
committed
Fix keySearch
1 parent eff5c6a commit 3955435

File tree

3 files changed

+29
-17
lines changed

3 files changed

+29
-17
lines changed

packages/kernel/src/utils/key-search.test.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ describe('keySearch', () => {
1313
it('returns the index of the first key greater than the search key', () => {
1414
const arr = ['a', 'c', 'e', 'g', 'i'];
1515
expect(keySearch(arr, 'b')).toBe(1);
16-
expect(keySearch(arr, 'd')).toBe(1);
17-
expect(keySearch(arr, 'f')).toBe(-1);
16+
expect(keySearch(arr, 'd')).toBe(2);
17+
expect(keySearch(arr, 'f')).toBe(3);
1818
});
1919

2020
it('returns 0 when the search key is less than the first element', () => {
@@ -71,7 +71,7 @@ describe('keySearch', () => {
7171
const arr = ['a', 'bb', 'ccc', 'dddd', 'eeeee'];
7272
expect(keySearch(arr, 'bb')).toBe(1);
7373
expect(keySearch(arr, 'b')).toBe(1);
74-
expect(keySearch(arr, 'cc')).toBe(1);
74+
expect(keySearch(arr, 'cc')).toBe(2);
7575
});
7676

7777
it('preserves lexicographic ordering', () => {

packages/kernel/src/utils/key-search.ts

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,31 +12,43 @@
1212
* `key`, or -1 if no such key exists.
1313
*/
1414
export function keySearch(arr: string[], key: string): number {
15-
if (arr === null) {
16-
// This shouldn't happen, but just in case...
15+
if (arr === null || arr.length === 0) {
1716
return -1;
1817
}
18+
1919
let beg = 0;
2020
let end = arr.length - 1;
21-
if (key < (arr[beg] as string)) {
22-
return beg;
21+
22+
// Key is less than first element
23+
if (key < (arr[0] as string)) {
24+
return 0;
2325
}
24-
if ((arr[end] as string) < key) {
26+
27+
// Key is greater than last element
28+
if (key > (arr[arr.length - 1] as string)) {
2529
return -1;
2630
}
27-
while (beg <= end) {
31+
32+
// Exact match with first element
33+
if (key === arr[0]) {
34+
return 0;
35+
}
36+
37+
// Binary search algorithm
38+
while (beg < end) {
2839
const mid = Math.floor((beg + end) / 2);
40+
41+
// Exact match
2942
if (arr[mid] === key) {
3043
return mid;
3144
}
45+
3246
if (key < (arr[mid] as string)) {
33-
end = mid - 1;
47+
end = mid;
3448
} else {
3549
beg = mid + 1;
3650
}
37-
if (beg === end) {
38-
return beg;
39-
}
4051
}
41-
return -1;
52+
53+
return beg;
4254
}

vitest.config.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -88,10 +88,10 @@ export default defineConfig({
8888
lines: 81.03,
8989
},
9090
'packages/kernel/**': {
91-
statements: 85.18,
91+
statements: 85.02,
9292
functions: 91.46,
93-
branches: 71.54,
94-
lines: 85.3,
93+
branches: 71.45,
94+
lines: 85.13,
9595
},
9696
'packages/nodejs/**': {
9797
statements: 72.91,

0 commit comments

Comments
 (0)