From 16f70c6e1a119926817a579747db0217f11effd6 Mon Sep 17 00:00:00 2001 From: "hugo.prunaux" Date: Fri, 20 Dec 2024 21:24:56 +0100 Subject: [PATCH] fix: gives minimum priority to the "void" character - This means that "a" will now come before "aa". - This reflects the behavior of `localeCompare`. --- test/compare.test.ts | 15 +++++++++++++++ utils/compare.ts | 9 ++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/test/compare.test.ts b/test/compare.test.ts index e2c9445fa..26865a10d 100644 --- a/test/compare.test.ts +++ b/test/compare.test.ts @@ -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 => diff --git a/utils/compare.ts b/utils/compare.ts index 13aba43c1..99a031958 100644 --- a/utils/compare.ts +++ b/utils/compare.ts @@ -122,9 +122,10 @@ let getCustomSortingFunction = ( 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) @@ -135,6 +136,12 @@ let getCustomSortingFunction = ( return convertBooleanToSign(indexOfA - indexOfB > 0) } } + if (aValue.length > bValue.length) { + return -1 + } + if (bValue.length > aValue.length) { + return 1 + } return 0 } }