Skip to content

Commit 73f0ab6

Browse files
committed
fix edge case in binary search
1 parent c89baab commit 73f0ab6

File tree

2 files changed

+11
-9
lines changed

2 files changed

+11
-9
lines changed

src/utils.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ export function binaryClosest(arr: Record<number | 'length', number>, num: numbe
1313
while (low <= high) {
1414
mid = (low + high) >> 1;
1515
item = arr[mid]!;
16+
if (item === num) {
17+
return mid;
18+
}
19+
1620
if (item > num) {
1721
high = mid - 1;
1822
} else if (item < num) {

test/TestWrapper.vue

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,15 @@
1414
</VirtualList>
1515
</div>
1616
<div>
17-
<input :value="gotoIndex" @input="onPositionInput" />
17+
<input
18+
type="number"
19+
v-model="gotoIndex" />
1820
</div>
1921
</template>
2022

2123
<script lang="ts">
2224
import { createVirtualScroller } from '../src/VirtualScroller';
23-
import { defineComponent, ref } from 'vue';
25+
import { defineComponent, ref, watch } from 'vue';
2426
import ExpandableThing from './ExpandableThing.vue';
2527
2628
const VirtualList = createVirtualScroller<TestItem>()
@@ -45,18 +47,14 @@ export default defineComponent({
4547
const scroller = ref<VirtualListInstance | null>(null);
4648
const gotoIndex = ref(0);
4749
48-
const onPositionInput = (e: Event) => {
49-
const value = Number((e.target as HTMLInputElement).value);
50-
if (!Number.isNaN(value)) {
51-
scroller.value?.scrollTo(value);
52-
}
53-
};
50+
watch(gotoIndex, () => {
51+
scroller.value?.scrollTo(gotoIndex.value);
52+
});
5453
5554
return {
5655
arr,
5756
scroller,
5857
gotoIndex,
59-
onPositionInput,
6058
}
6159
}
6260
});

0 commit comments

Comments
 (0)