Skip to content

Commit

Permalink
Fix bug with memoized binary search's found state
Browse files Browse the repository at this point in the history
If an intermediate search happens, then the `found` state will be the result of _that_ search and
not the memoized one we just skipped.
  • Loading branch information
jridgewell committed Apr 20, 2022
1 parent d9e245c commit 5596de1
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/any-map.ts
Expand Up @@ -32,7 +32,7 @@ export const AnyMap: AnyMap = function (map, mapUrl) {
const no = sections[i + 1].offset;
addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, no.line, no.column);
}
for (; i < sections.length; i++) {
if (sections.length > 0) {
addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, -1, -1);
}

Expand Down
1 change: 1 addition & 0 deletions src/binary-search.ts
Expand Up @@ -97,6 +97,7 @@ export function memoizedBinarySearch(
let high = haystack.length - 1;
if (key === lastKey) {
if (needle === lastNeedle) {
found = haystack[lastIndex][COLUMN] === needle;
return lastIndex;
}

Expand Down
23 changes: 22 additions & 1 deletion test/binary-search.test.ts
@@ -1,4 +1,4 @@
import { binarySearch } from '../src/binary-search';
import { binarySearch, found, memoizedState, memoizedBinarySearch } from '../src/binary-search';
import { test, describe } from './setup';

type SourceMapSegment = [number];
Expand Down Expand Up @@ -376,3 +376,24 @@ describe('binary search', () => {
});
});
});

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

test('refinds same index', (t) => {
const memo = memoizedState();

t.is(memoizedBinarySearch(array, 6, memo, 0), 1);
t.is(memoizedBinarySearch(array, 6, memo, 0), 1);
});

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

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

0 comments on commit 5596de1

Please sign in to comment.