Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

originalPositionFor() API fix for indexed maps: faster due to not executing a useless=buggy comparison near the end in binary search #392

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions lib/binary-search.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
// 3. We did not find the exact element, and there is no next-closest
// element than the one we are searching for, so we return -1.
const mid = Math.floor((aHigh - aLow) / 2) + aLow;
const cmp = aCompare(aNeedle, aHaystack[mid], true);
const cmp = aCompare(aNeedle, aHaystack[mid]);
if (cmp === 0) {
// Found the element we are looking for.
return mid;
Expand Down Expand Up @@ -95,9 +95,10 @@ exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {

// We have found either the exact element, or the next-closest element than
// the one we are searching for. However, there may be more than one such
// element. Make sure we always return the smallest of these.
// element ONLY IFF we found an exact match.
// Make sure we always return the smallest of these.
while (index - 1 >= 0) {
if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
if (aCompare(aNeedle, aHaystack[index - 1]) !== 0) {
break;
}
--index;
Expand Down
26 changes: 26 additions & 0 deletions test/test-binary-search.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,29 @@ exports["test multiple matches at the beginning"] = function(assert) {
assert.equal(binarySearch.search(needle, haystack, numberCompare,
binarySearch.LEAST_UPPER_BOUND), 0);
};

exports["test fuzzy match with duplicates in the data at match point"] = function(assert) {
const needle = 2;
const haystack = [1, 1, 5, 5, 5, 5, 13, 21];

assert.equal(
binarySearch.search(
needle,
haystack,
numberCompare,
binarySearch.LEAST_UPPER_BOUND
),
2
);

assert.equal(
binarySearch.search(
needle,
haystack,
numberCompare,
binarySearch.GREATEST_LOWER_BOUND
),
1
);
};