Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8828b84

Browse files
author
Dan Kaplun
committed
Adds key function to binarysearch.js
If an element is not found, return -x - 1 where x is the index into which the element should be inserted Closes mgechev#36
1 parent 8cab588 commit 8828b84

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

src/searching/binarysearch.js

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,22 +18,27 @@
1818
* @param {Number} value Value of the element which index should be found.
1919
* @returns {Number} Index of the element or -1 if not found.
2020
*/
21-
function binarySearch(array, value) {
21+
function binarySearch(array, value, key) {
22+
key = !key ? id : typeof key === 'string' ? get(key) : key;
23+
value = key(value);
2224
var middle = Math.floor(array.length / 2);
2325
var left = 0;
2426
var right = array.length;
2527
while (right >= left) {
26-
if (array[middle] === value) {
28+
var middleValue = key(array[middle]);
29+
if (middleValue === value) {
2730
return middle;
28-
} else if (array[middle] > value) {
31+
} else if (middleValue > value) {
2932
right = middle - 1;
3033
} else {
3134
left = middle + 1;
3235
}
3336
middle = Math.floor((left + right) / 2);
3437
}
35-
return -1;
38+
return -middle - 1;
3639
}
40+
function id (val) { return val; }
41+
function get (key) { return function (val) { return val[key]; }; }
3742

3843
exports.binarySearch = binarySearch;
3944

test/searching/binarysearch.spec.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,19 @@ describe('Binary search', function () {
1818
expect(binarySearch([1, 8], 8)).toBe(1);
1919
});
2020

21-
it('should return -1 for missing elements', function () {
22-
expect(binarySearch([1, 2, 3], 4)).toBe(-1);
21+
it('should return a negative number for missing elements', function () {
22+
expect(binarySearch([1, 2, 3], 4)).toBeLessThan(0);
2323
});
2424

2525
it('should work with empty arrays', function () {
2626
expect(binarySearch([], 4)).toBe(-1);
2727
});
28+
29+
it('should work with a key string', function () {
30+
expect(binarySearch([{ x: 1 }, { x: 2 }, { x: 3 }], { x: 2 }, 'x')).toBe(1);
31+
});
32+
33+
it('should work with a key function', function () {
34+
expect(binarySearch([{ x: 1 }, { x: 2 }, { x: 3 }], { x: 2 }, function (o) { return o.x; })).toBe(1);
35+
});
2836
});

0 commit comments

Comments
 (0)