From 389c635030553b0141c831830acf2a936bf17ecb Mon Sep 17 00:00:00 2001 From: Carlos Alcaide Corvo Date: Fri, 11 Jul 2025 10:08:39 -0700 Subject: [PATCH] Modify string sorting to benefit upperCase (#2924) * Modify the string sorting to benefit uppercase over lowercase at comparison --- addons/api/addon/utils/sort-results.js | 5 +- .../api/tests/unit/utils/sort-results-test.js | 46 +++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/addons/api/addon/utils/sort-results.js b/addons/api/addon/utils/sort-results.js index da876b4d6..a59dc94ea 100644 --- a/addons/api/addon/utils/sort-results.js +++ b/addons/api/addon/utils/sort-results.js @@ -10,7 +10,10 @@ const SORT_DIRECTION_ASCENDING = 'asc'; const SORT_DIRECTION_DESCENDING = 'desc'; const sortFunctions = { - string: (a, b) => String(a).localeCompare(String(b)), + string: (a, b) => + String(a).localeCompare(String(b), navigator.language, { + caseFirst: 'upper', + }), date: (a, b) => new Date(a).getTime() - new Date(b).getTime(), number: (a, b) => Number(a) - Number(b), boolean: (a, b) => Number(a) - Number(b), diff --git a/addons/api/tests/unit/utils/sort-results-test.js b/addons/api/tests/unit/utils/sort-results-test.js index b13746b35..364758dfd 100644 --- a/addons/api/tests/unit/utils/sort-results-test.js +++ b/addons/api/tests/unit/utils/sort-results-test.js @@ -203,6 +203,52 @@ module('Unit | Utility | sortResults', function (hooks) { ['Result 04', 'Result 03', 'Result 02', 'Result 01'], ); }); + + test('it sorts by ascending then descending `name` using string sorting with Upper case preference', async function (assert) { + const result01 = createJsonApiMockRecord('id_01', 'target', { + name: 'orange', + }); + const result02 = createJsonApiMockRecord('id_02', 'target', { + name: 'Orange', + }); + const result03 = createJsonApiMockRecord('id_03', 'target', { + name: 'banana', + }); + const result04 = createJsonApiMockRecord('id_04', 'target', { + name: 'Banana', + }); + const result05 = createJsonApiMockRecord('id_04', 'target', { + name: 'apple', + }); + const shuffledResults = faker.helpers.shuffle([ + result01, + result02, + result03, + result04, + result05, + ]); + const querySortAsc = { attribute: 'name', direction: 'asc' }; + const querySortDesc = { attribute: 'name', direction: 'desc' }; + const schema = { attributes: new Map() }; + schema.attributes.set('name', { type: 'string' }); + + const sortedResultsAsc = sortResults(shuffledResults, { + querySort: querySortAsc, + schema, + }); + const sortedResultsDesc = sortResults(shuffledResults, { + querySort: querySortDesc, + schema, + }); + assert.deepEqual( + sortedResultsAsc.map(({ attributes: { name } }) => name), + ['apple', 'Banana', 'banana', 'Orange', 'orange'], + ); + assert.deepEqual( + sortedResultsDesc.map(({ attributes: { name } }) => name), + ['orange', 'Orange', 'banana', 'Banana', 'apple'], + ); + }); }); module('date sorting', function () {