Skip to content

Commit 3fb34fc

Browse files
authoredOct 17, 2024··
fix(sort-switch-case): fixe expressions being ignored
1 parent 998968a commit 3fb34fc

File tree

2 files changed

+49
-12
lines changed

2 files changed

+49
-12
lines changed
 

‎rules/sort-switch-case.ts

+3-2
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,8 @@ export default createEslintRule<Options, MESSAGE_ID>({
9393

9494
let sourceCode = getSourceCode(context)
9595

96-
let isDiscriminantIdentifier = node.discriminant.type === 'Identifier'
96+
let isDiscriminantTrue =
97+
node.discriminant.type === 'Literal' && node.discriminant.value === true
9798
let isCasesHasBreak = node.cases
9899
.filter(caseNode => caseNode.test !== null)
99100
.every(
@@ -107,7 +108,7 @@ export default createEslintRule<Options, MESSAGE_ID>({
107108
),
108109
)
109110

110-
if (isDiscriminantIdentifier && isCasesHasBreak) {
111+
if (!isDiscriminantTrue && isCasesHasBreak) {
111112
let nodes = node.cases.map<SortSwitchCaseSortingNode>(
112113
(caseNode: TSESTree.SwitchCase) => {
113114
let name: string

‎test/sort-switch-case.test.ts

+46-10
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,46 @@ describe(ruleName, () => {
4949
},
5050
],
5151
invalid: [
52+
{
53+
code: dedent`
54+
function func(name) {
55+
switch(<any> myFunc(a! + b?.c as any)) {
56+
case 'bb':
57+
return 'b'
58+
case 'aaa':
59+
return 'a'
60+
case 'c':
61+
return 'c'
62+
default:
63+
return 'x'
64+
}
65+
}
66+
`,
67+
output: dedent`
68+
function func(name) {
69+
switch(<any> myFunc(a! + b?.c as any)) {
70+
case 'aaa':
71+
return 'a'
72+
case 'bb':
73+
return 'b'
74+
case 'c':
75+
return 'c'
76+
default:
77+
return 'x'
78+
}
79+
}
80+
`,
81+
options: [options],
82+
errors: [
83+
{
84+
messageId: 'unexpectedSwitchCaseOrder',
85+
data: {
86+
left: 'bb',
87+
right: 'aaa',
88+
},
89+
},
90+
],
91+
},
5292
{
5393
code: dedent`
5494
function func(name) {
@@ -1867,12 +1907,9 @@ describe(ruleName, () => {
18671907
})
18681908

18691909
describe(`${ruleName}: misc`, () => {
1870-
ruleTester.run(
1871-
`${ruleName}: not works if discriminant is not literal`,
1872-
rule,
1873-
{
1874-
valid: [
1875-
dedent`
1910+
ruleTester.run(`${ruleName}: not works if discriminant is true`, rule, {
1911+
valid: [
1912+
dedent`
18761913
switch (true) {
18771914
case name === 'bb':
18781915
return 'b'
@@ -1884,10 +1921,9 @@ describe(ruleName, () => {
18841921
return 'x'
18851922
}
18861923
`,
1887-
],
1888-
invalid: [],
1889-
},
1890-
)
1924+
],
1925+
invalid: [],
1926+
})
18911927
})
18921928

18931929
ruleTester.run(`${ruleName}: default should be last`, rule, {

0 commit comments

Comments
 (0)
Please sign in to comment.