]>
git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/sort-vars.js
ec0718ee578c742c3f3dedad3da7c94acf7d36c5
2 * @fileoverview Rule to require sorting of variables within a single Variable Declaration block
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 /** @type {import('../shared/types').Rule} */
18 description
: "Require variables within the same declaration block to be sorted",
20 url
: "https://eslint.org/docs/rules/sort-vars"
32 additionalProperties
: false
39 sortVars
: "Variables within the same declaration block should be sorted alphabetically."
45 const configuration
= context
.options
[0] || {},
46 ignoreCase
= configuration
.ignoreCase
|| false,
47 sourceCode
= context
.getSourceCode();
50 VariableDeclaration(node
) {
51 const idDeclarations
= node
.declarations
.filter(decl
=> decl
.id
.type
=== "Identifier");
52 const getSortableName
= ignoreCase
? decl
=> decl
.id
.name
.toLowerCase() : decl
=> decl
.id
.name
;
53 const unfixable
= idDeclarations
.some(decl
=> decl
.init
!== null && decl
.init
.type
!== "Literal");
56 idDeclarations
.slice(1).reduce((memo
, decl
) => {
57 const lastVariableName
= getSortableName(memo
),
58 currentVariableName
= getSortableName(decl
);
60 if (currentVariableName
< lastVariableName
) {
63 messageId
: "sortVars",
65 if (unfixable
|| fixed
) {
68 return fixer
.replaceTextRange(
69 [idDeclarations
[0].range
[0], idDeclarations
[idDeclarations
.length
- 1].range
[1]],
72 // Clone the idDeclarations array to avoid mutating it
75 // Sort the array into the desired order
76 .sort((declA
, declB
) => {
77 const aName
= getSortableName(declA
);
78 const bName
= getSortableName(declB
);
80 return aName
> bName
? 1 : -1;
83 // Build a string out of the sorted list of identifier declarations and the text between the originals
84 .reduce((sourceText
, identifier
, index
) => {
85 const textAfterIdentifier
= index
=== idDeclarations
.length
- 1
87 : sourceCode
.getText().slice(idDeclarations
[index
].range
[1], idDeclarations
[index
+ 1].range
[0]);
89 return sourceText
+ sourceCode
.getText(identifier
) + textAfterIdentifier
;
100 }, idDeclarations
[0]);