Skip to content

Commit

Permalink
Fix bug with memoized binary search's found state, part 2
Browse files Browse the repository at this point in the history
Fixes #4
  • Loading branch information
jridgewell committed Apr 20, 2022
1 parent bcbd2de commit 589574e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/binary-search.ts
Expand Up @@ -97,7 +97,7 @@ export function memoizedBinarySearch(
let high = haystack.length - 1;
if (key === lastKey) {
if (needle === lastNeedle) {
found = haystack[lastIndex][COLUMN] === needle;
found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
return lastIndex;
}

Expand Down
17 changes: 12 additions & 5 deletions test/binary-search.test.ts
Expand Up @@ -378,7 +378,7 @@ describe('binary search', () => {
});

describe('memoizedBinarySearch', () => {
const array: SourceMapSegment[] = [[0], [5], [10]];
const array: SourceMapSegment[] = [[1], [5], [10]];

test('refinds same index', (t) => {
const memo = memoizedState();
Expand All @@ -388,12 +388,19 @@ describe('memoizedBinarySearch', () => {
});

test('restores found state', (t) => {
const memo = memoizedState();
const memo1 = memoizedState();
const memo2 = memoizedState();

t.is(memoizedBinarySearch(array, 6, memo, 0), 1);
binarySearch(array, 0, 0, array.length - 1);
t.is(memoizedBinarySearch(array, 0, memo1, 0), -1);
t.is(found, false);

t.is(memoizedBinarySearch(array, 5, memo2, 0), 1);
t.is(found, true);
t.is(memoizedBinarySearch(array, 6, memo, 0), 1);

t.is(memoizedBinarySearch(array, 0, memo1, 0), -1);
t.is(found, false);

t.is(memoizedBinarySearch(array, 5, memo2, 0), 1);
t.is(found, true);
});
});

0 comments on commit 589574e

Please sign in to comment.