UNPKG

4.13 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to require sorting of variables within a single Variable Declaration block
3 * @author Ilya Volodin
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Rule Definition
10//------------------------------------------------------------------------------
11
12module.exports = {
13 meta: {
14 type: "suggestion",
15
16 docs: {
17 description: "require variables within the same declaration block to be sorted",
18 category: "Stylistic Issues",
19 recommended: false,
20 url: "https://eslint.org/docs/rules/sort-vars"
21 },
22
23 schema: [
24 {
25 type: "object",
26 properties: {
27 ignoreCase: {
28 type: "boolean",
29 default: false
30 }
31 },
32 additionalProperties: false
33 }
34 ],
35
36 fixable: "code",
37
38 messages: {
39 sortVars: "Variables within the same declaration block should be sorted alphabetically."
40 }
41 },
42
43 create(context) {
44
45 const configuration = context.options[0] || {},
46 ignoreCase = configuration.ignoreCase || false,
47 sourceCode = context.getSourceCode();
48
49 return {
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");
54 let fixed = false;
55
56 idDeclarations.slice(1).reduce((memo, decl) => {
57 const lastVariableName = getSortableName(memo),
58 currentVariableName = getSortableName(decl);
59
60 if (currentVariableName < lastVariableName) {
61 context.report({
62 node: decl,
63 messageId: "sortVars",
64 fix(fixer) {
65 if (unfixable || fixed) {
66 return null;
67 }
68 return fixer.replaceTextRange(
69 [idDeclarations[0].range[0], idDeclarations[idDeclarations.length - 1].range[1]],
70 idDeclarations
71
72 // Clone the idDeclarations array to avoid mutating it
73 .slice()
74
75 // Sort the array into the desired order
76 .sort((declA, declB) => {
77 const aName = getSortableName(declA);
78 const bName = getSortableName(declB);
79
80 return aName > bName ? 1 : -1;
81 })
82
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
86 ? ""
87 : sourceCode.getText().slice(idDeclarations[index].range[1], idDeclarations[index + 1].range[0]);
88
89 return sourceText + sourceCode.getText(identifier) + textAfterIdentifier;
90 }, "")
91
92 );
93 }
94 });
95 fixed = true;
96 return memo;
97 }
98 return decl;
99
100 }, idDeclarations[0]);
101 }
102 };
103 }
104};