Skip to content

Commit

Permalink
fix: Handle case where different strings with leading zeros have the …
Browse files Browse the repository at this point in the history
…same length

Before: naturalCompare('a0a00a', 'a00a0a') === 0
Now: naturalCompare('a0a00a', 'a00a0a') < 0
  • Loading branch information
nwoltman committed Jan 21, 2020
1 parent 9263689 commit 7d5a4ae
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
7 changes: 6 additions & 1 deletion natural-compare.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ function naturalCompare(a, b, opts) {
let indexA = 0;
let indexB = 0;
let alphabetIndexMap = defaultAlphabetIndexMap;
let firstDifferenceInLeadingZeros = 0;

if (opts) {
if (opts.caseInsensitive) {
Expand Down Expand Up @@ -50,6 +51,10 @@ function naturalCompare(a, b, opts) {
charCodeB = b.charCodeAt(numStartB);
}

if (numStartA !== numStartB && firstDifferenceInLeadingZeros === 0) {
firstDifferenceInLeadingZeros = numStartA - numStartB;
}

let numEndA = numStartA;
let numEndB = numStartB;

Expand Down Expand Up @@ -102,7 +107,7 @@ function naturalCompare(a, b, opts) {
return -1;
}

return lengthA - lengthB;
return firstDifferenceInLeadingZeros;
}

const alphabetIndexMapCache = {};
Expand Down
5 changes: 5 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,12 @@ describe('naturalCompare()', () => {
['a0a', '>', 'a00'],
['a0a', '>', 'a000'],
['a0a', '<', 'a0b'],
['a0a', '<', 'a00a'],
['a0a', '<', 'a00b'],
['a00a', '<', 'a0b'],
['a00a0a', '<', 'a0a00b'],
['a0a00b', '<', 'a00a0b'],
['a00a0b', '>', 'a0a00b'],
].forEach(verify);
});

Expand Down

0 comments on commit 7d5a4ae

Please sign in to comment.