diff --git a/lib/search/binary.js b/lib/search/binary.js index 704f37d..364f947 100644 --- a/lib/search/binary.js +++ b/lib/search/binary.js @@ -23,16 +23,19 @@ module.exports = binary; function binary(array, value) { var low = -1; var high = array.length; + var midpoint; while (high - low > 1) { - var midpoint = high + low >> 1; + midpoint = high + low >> 1; if (array[midpoint] > value) { high = midpoint; } else if (array[midpoint] < value) { low = midpoint; } else { - return array[midpoint] === value ? value : undefined; + break; } } + + return array[midpoint] === value ? value : undefined; } diff --git a/lib/search/test/binary-test.js b/lib/search/test/binary-test.js index 52c4978..72fb640 100644 --- a/lib/search/test/binary-test.js +++ b/lib/search/test/binary-test.js @@ -2,6 +2,8 @@ var test = require('tape'); var binary = require('../binary'); test('binary(array, value)', function (t) { + t.equal(binary([]), undefined, 'should return undefined'); + t.equal(binary([1, 10], 0), undefined, 'should return undefined'); t.equal(binary([1, 2, 3, 4, 5], 3), 3, 'should return 3'); t.equal(binary(['a', 'b', 'c', 'd', 'e', 'f'], 'd'), 'd', 'should return d'); t.end(); diff --git a/lib/search/test/linear-test.js b/lib/search/test/linear-test.js index 34d5d81..ee25284 100644 --- a/lib/search/test/linear-test.js +++ b/lib/search/test/linear-test.js @@ -2,6 +2,8 @@ var test = require('tape'); var linear = require('../linear'); test('linear(array, value)', function (t) { + t.equal(linear([]), undefined, 'should return undefined'); + t.equal(linear([1, 10], 0), undefined, 'should return undefined'); t.equal(linear([1, 2, 3, 4, 5], 3), 3, 'should return 3'); t.equal(linear(['c', 'a', 'b'], 'a'), 'a', 'should return a'); t.equal(linear(['foo', 'bar', 'baz'], 'foo'), 'foo', 'should return foo');