Skip to content

Commit

Permalink
[Fix] order: fix alphabetical sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
geraintwhite committed May 14, 2021
1 parent 8213543 commit 389a37f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
13 changes: 8 additions & 5 deletions src/rules/order.js
Expand Up @@ -265,14 +265,17 @@ function mutateRanksToAlphabetize(imported, alphabetizeOptions) {
if (!Array.isArray(acc[importedItem.rank])) {
acc[importedItem.rank] = [];
}
acc[importedItem.rank].push(`${importedItem.value}-${importedItem.node.importKind}`);
acc[importedItem.rank].push(importedItem);
return acc;
}, {});

const groupRanks = Object.keys(groupedByRanks);

const sorterFn = getSorter(alphabetizeOptions.order === 'asc');
const comparator = alphabetizeOptions.caseInsensitive ? (a, b) => sorterFn(String(a).toLowerCase(), String(b).toLowerCase()) : (a, b) => sorterFn(a, b);
const comparator = alphabetizeOptions.caseInsensitive
? (a, b) => sorterFn(String(a.value).toLowerCase(), String(b.value).toLowerCase())
: (a, b) => sorterFn(a.value, b.value);

// sort imports locally within their group
groupRanks.forEach(function(groupRank) {
groupedByRanks[groupRank].sort(comparator);
Expand All @@ -281,16 +284,16 @@ function mutateRanksToAlphabetize(imported, alphabetizeOptions) {
// assign globally unique rank to each import
let newRank = 0;
const alphabetizedRanks = groupRanks.sort().reduce(function(acc, groupRank) {
groupedByRanks[groupRank].forEach(function(importedItemName) {
acc[importedItemName] = parseInt(groupRank, 10) + newRank;
groupedByRanks[groupRank].forEach(function(importedItem) {
acc[`${importedItem.value}|${importedItem.node.importKind}`] = parseInt(groupRank, 10) + newRank;
newRank += 1;
});
return acc;
}, {});

// mutate the original group-rank with alphabetized-rank
imported.forEach(function(importedItem) {
importedItem.rank = alphabetizedRanks[`${importedItem.value}-${importedItem.node.importKind}`];
importedItem.rank = alphabetizedRanks[`${importedItem.value}|${importedItem.node.importKind}`];
});
}

Expand Down
14 changes: 14 additions & 0 deletions tests/src/rules/order.js
Expand Up @@ -706,6 +706,20 @@ ruleTester.run('order', rule, {
},
],
}),
// Order of imports with similar names
test({
code: `
import React from 'react';
import { BrowserRouter } from 'react-router-dom';
`,
options: [
{
alphabetize: {
order: 'asc',
},
},
],
}),
...flatMap(getTSParsers, parser => [
// Order of the `import ... = require(...)` syntax
test({
Expand Down

0 comments on commit 389a37f

Please sign in to comment.