diff --git a/.gitignore b/.gitignore index d321659..57c96f5 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,5 @@ atlassian-ide-plugin.xml npm-debug.log report/ node_modules/ -out/ \ No newline at end of file +out/ +package-lock.json diff --git a/sorted-array.js b/sorted-array.js index d2311a4..a75d731 100644 --- a/sorted-array.js +++ b/sorted-array.js @@ -108,8 +108,7 @@ function searchForInsertionIndex(array, value, compare) { if (index < 0) { return -index - 1; } else { - var last = array.length - 1; - while (index < last && compare(value, array[index + 1]) === 0) { + while (index < array.length && compare(value, array[index]) === 0) { index++; } return index; diff --git a/test/spec/sorted-array-spec.js b/test/spec/sorted-array-spec.js index b87c467..c987999 100644 --- a/test/spec/sorted-array-spec.js +++ b/test/spec/sorted-array-spec.js @@ -37,6 +37,30 @@ describe("SortedArray-spec", function () { }); }); + describe("stable", function () { + let collection; + + beforeEach(() => { + collection = new SortedArray([{k:0, v:"a"}, {k:1, v:"b"}], null, function(a, b) { + return a.k - b.k; + }); + }); + + it("should add at the end of sequence", function () { + collection.add({k:1, v:"q"}); + expect(collection.toArray()[0].v).toBe("a") + expect(collection.toArray()[1].v).toBe("b") + expect(collection.toArray()[2].v).toBe("q") + }); + + it("should add at the end of subsequence", function () { + collection.add({k:0, v:"q"}); + expect(collection.toArray()[0].v).toBe("a") + expect(collection.toArray()[1].v).toBe("q") + expect(collection.toArray()[2].v).toBe("b") + }); + }) + describe("incomparable values", function () { function customEquals(one, two) { return one.id === two.id;