diff --git a/lib/rules/sort-destructure-keys.js b/lib/rules/sort-destructure-keys.js index 841772c..b3c5fde 100644 --- a/lib/rules/sort-destructure-keys.js +++ b/lib/rules/sort-destructure-keys.js @@ -34,6 +34,7 @@ const NODE_TYPE_SORT_ORDER = { ExperimentalRestProperty: 99, /* Property keys */ + ALL_CAPS_KEY: 0, Identifier: 1, Literal: 1, TemplateLiteral: 2, @@ -43,9 +44,13 @@ const NODE_TYPE_SORT_ORDER = { const SORT_ORDER_DEFAULT = 98; function getSortOrder(node) { - return isComputedProperty(node) - ? NODE_TYPE_SORT_ORDER.ComputedProperty - : NODE_TYPE_SORT_ORDER[node.type] || SORT_ORDER_DEFAULT; + if (isAllCaps(getNodeName(node))) return NODE_TYPE_SORT_ORDER.ALL_CAPS_KEY; + if (isComputedProperty(node)) return NODE_TYPE_SORT_ORDER.ComputedProperty; + return NODE_TYPE_SORT_ORDER[node.type] || SORT_ORDER_DEFAULT; +} + +function isAllCaps(key) { + return /^[A-Z_]+$/.test(key); } /** @@ -140,13 +145,28 @@ function createSorter(caseSensitive) { return (a, b) => { // When we have different node "types" + const nodeResult = getSortOrder(a) - getSortOrder(b); if (nodeResult !== 0) return nodeResult; // When the keys have different "types" const keyResult = getSortOrder(a.key) - getSortOrder(b.key); + if (keyResult !== 0) return keyResult; + // Handle ALL_CAPS special cases + const isAAllCaps = getSortOrder(a) === 0; + const isBAllCaps = getSortOrder(b) === 0; + + if (isAAllCaps && isBAllCaps) { + // Both ALL_CAPS: compare directly + return getNodeName(a).localeCompare(getNodeName(b)); + } + + if (isAAllCaps || isBAllCaps) { + // If either is ALL_CAPS but not both: keep original order + return 0; + } return naturalCompare(sortName(getNodeName(a)), sortName(getNodeName(b))); }; } @@ -159,6 +179,7 @@ function createFix({ context, fixer, node, sorter }) { const sourceText = sourceCode.getText(); const sorted = node.properties.concat().sort(sorter); + console.log({ sorted }); const newText = sorted .map((child, i) => { diff --git a/tests/lib/rules/sort-destructure-keys.js b/tests/lib/rules/sort-destructure-keys.js index 37b4698..4b8aae6 100644 --- a/tests/lib/rules/sort-destructure-keys.js +++ b/tests/lib/rules/sort-destructure-keys.js @@ -322,6 +322,17 @@ function testsWithParser(parser, parserOptions = {}) { ], }); + testsFor("capitalized variables", { + valid: ["const { LAST_NAME, NAME_FIRST, Motto, a, b } = someObject;"], + invalid: [ + { + code: "const { NAME_FIRST, Motto, LAST_NAME, b, a } = someObject;", + errors: just("Motto", "LAST_NAME"), + output: "const { LAST_NAME, NAME_FIRST, Motto, a, b } = someObject;", + }, + ], + }); + describe("options", () => { testsFor("caseSensitive", { valid: [