Skip to content

Commit

Permalink
Always return the smallest element when there is more than one match.
Browse files Browse the repository at this point in the history
  • Loading branch information
ejpbruel committed Feb 27, 2015
1 parent 07f6b81 commit 5241b06
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 4 deletions.
19 changes: 17 additions & 2 deletions lib/source-map/binary-search.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,23 @@ define(function (require, exports, module) {
return -1;
}

return recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare,
aBias || exports.GREATEST_LOWER_BOUND);
var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
aCompare, aBias || exports.GREATEST_LOWER_BOUND);
if (index < 0) {
return -1;
}

// 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.
while (index - 1 >= 0) {
if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
break;
}
--index;
}

return index;
};

});
4 changes: 2 additions & 2 deletions lib/source-map/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ define(function (require, exports, module) {
return cmp;
}

cmp = strcmp(mappingA.name, mappingB.name);
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp) {
return cmp;
}
Expand All @@ -271,7 +271,7 @@ define(function (require, exports, module) {
return cmp;
}

return mappingA.generatedColumn - mappingB.generatedColumn;
return strcmp(mappingA.name, mappingB.name);
};
exports.compareByOriginalPositions = compareByOriginalPositions;

Expand Down
16 changes: 16 additions & 0 deletions test/source-map/test-binary-search.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,20 @@ define(function (require, exports, module) {
binarySearch.LEAST_UPPER_BOUND)], 20);
};

exports['test multiple matches'] = function (assert, util) {
var needle = 5;
var haystack = [1, 1, 2, 5, 5, 5, 13, 21];

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

exports['test multiple matches at the beginning'] = function (assert, util) {
var needle = 1;
var haystack = [1, 1, 2, 5, 5, 5, 13, 21];

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

});

0 comments on commit 5241b06

Please sign in to comment.