diff --git a/js/misc/util.js b/js/misc/util.js index 36640580b..8673f8329 100644 --- a/js/misc/util.js +++ b/js/misc/util.js @@ -265,7 +265,7 @@ function lowerBound(array, val, cmp) { max = mid; } - return (cmp(array[min], val) < 0) ? max : min; + return (min == max || cmp(array[min], val) < 0) ? max : min; } // insertSorted: diff --git a/tests/unit/insertSorted.js b/tests/unit/insertSorted.js index e23848a22..610aeed56 100644 --- a/tests/unit/insertSorted.js +++ b/tests/unit/insertSorted.js @@ -64,8 +64,13 @@ let arrayEmpty = []; // inserting in a empty array Util.insertSorted(arrayEmpty, 3, checkedCmp); +// Insert at the end and check that we don't +// access past it +Util.insertSorted(arrayEmpty, 4, checkedCmp); +Util.insertSorted(arrayEmpty, 5, checkedCmp); + // Some more insertions Util.insertSorted(arrayEmpty, 2, checkedCmp); Util.insertSorted(arrayEmpty, 1, checkedCmp); -assertArrayEquals('checkedCmp test', [1, 2, 3], arrayEmpty); +assertArrayEquals('checkedCmp test', [1, 2, 3, 4, 5], arrayEmpty);