Skip to content

Commit

Permalink
fix: gives minimum priority to the "void" character
Browse files Browse the repository at this point in the history
- This means that "a" will now come before "aa".
- This reflects the behavior of `localeCompare`.
  • Loading branch information
hugop95 committed Dec 20, 2024
1 parent 5576614 commit 16f70c6
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
15 changes: 15 additions & 0 deletions test/compare.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,21 @@ describe('compare', () => {
}),
).toBe(0)
})

it('gives minimum priority to void', () => {
expect(
compare(createTestNode({ name: 'a' }), createTestNode({ name: '' }), {
...compareOptions,
alphabet: 'a',
}),
).toBe(-1)
expect(
compare(createTestNode({ name: '' }), createTestNode({ name: 'a' }), {
...compareOptions,
alphabet: 'a',
}),
).toBe(1)
})
})

let createTestNode = ({ name }: { name: string }): SortingNode =>
Expand Down
9 changes: 8 additions & 1 deletion utils/compare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,10 @@ let getCustomSortingFunction = <T extends SortingNode>(
return (aNode: T, bNode: T) => {
let aValue = formatString(nodeValueGetter(aNode))
let bValue = formatString(nodeValueGetter(bNode))
let minLength = Math.min(aValue.length, bValue.length)
// Iterate character by character
// eslint-disable-next-line unicorn/no-for-loop
for (let i = 0; i < aValue.length; i++) {
for (let i = 0; i < minLength; i++) {
let aCharacter = aValue[i]
let bCharacter = bValue[i]
let indexOfA = indexByCharacters.get(aCharacter)
Expand All @@ -135,6 +136,12 @@ let getCustomSortingFunction = <T extends SortingNode>(
return convertBooleanToSign(indexOfA - indexOfB > 0)
}
}
if (aValue.length > bValue.length) {
return -1
}
if (bValue.length > aValue.length) {
return 1
}
return 0
}
}
Expand Down

0 comments on commit 16f70c6

Please sign in to comment.