Skip to content

Commit 389a37f

Browse files
committed
[Fix] order: fix alphabetical sorting
1 parent 8213543 commit 389a37f

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

Diff for: src/rules/order.js

+8-5
Original file line numberDiff line numberDiff line change
@@ -265,14 +265,17 @@ function mutateRanksToAlphabetize(imported, alphabetizeOptions) {
265265
if (!Array.isArray(acc[importedItem.rank])) {
266266
acc[importedItem.rank] = [];
267267
}
268-
acc[importedItem.rank].push(`${importedItem.value}-${importedItem.node.importKind}`);
268+
acc[importedItem.rank].push(importedItem);
269269
return acc;
270270
}, {});
271271

272272
const groupRanks = Object.keys(groupedByRanks);
273273

274274
const sorterFn = getSorter(alphabetizeOptions.order === 'asc');
275-
const comparator = alphabetizeOptions.caseInsensitive ? (a, b) => sorterFn(String(a).toLowerCase(), String(b).toLowerCase()) : (a, b) => sorterFn(a, b);
275+
const comparator = alphabetizeOptions.caseInsensitive
276+
? (a, b) => sorterFn(String(a.value).toLowerCase(), String(b.value).toLowerCase())
277+
: (a, b) => sorterFn(a.value, b.value);
278+
276279
// sort imports locally within their group
277280
groupRanks.forEach(function(groupRank) {
278281
groupedByRanks[groupRank].sort(comparator);
@@ -281,16 +284,16 @@ function mutateRanksToAlphabetize(imported, alphabetizeOptions) {
281284
// assign globally unique rank to each import
282285
let newRank = 0;
283286
const alphabetizedRanks = groupRanks.sort().reduce(function(acc, groupRank) {
284-
groupedByRanks[groupRank].forEach(function(importedItemName) {
285-
acc[importedItemName] = parseInt(groupRank, 10) + newRank;
287+
groupedByRanks[groupRank].forEach(function(importedItem) {
288+
acc[`${importedItem.value}|${importedItem.node.importKind}`] = parseInt(groupRank, 10) + newRank;
286289
newRank += 1;
287290
});
288291
return acc;
289292
}, {});
290293

291294
// mutate the original group-rank with alphabetized-rank
292295
imported.forEach(function(importedItem) {
293-
importedItem.rank = alphabetizedRanks[`${importedItem.value}-${importedItem.node.importKind}`];
296+
importedItem.rank = alphabetizedRanks[`${importedItem.value}|${importedItem.node.importKind}`];
294297
});
295298
}
296299

Diff for: tests/src/rules/order.js

+14
Original file line numberDiff line numberDiff line change
@@ -706,6 +706,20 @@ ruleTester.run('order', rule, {
706706
},
707707
],
708708
}),
709+
// Order of imports with similar names
710+
test({
711+
code: `
712+
import React from 'react';
713+
import { BrowserRouter } from 'react-router-dom';
714+
`,
715+
options: [
716+
{
717+
alphabetize: {
718+
order: 'asc',
719+
},
720+
},
721+
],
722+
}),
709723
...flatMap(getTSParsers, parser => [
710724
// Order of the `import ... = require(...)` syntax
711725
test({

0 commit comments

Comments
 (0)