1 | /**
|
2 | * @fileoverview Rule to check multiple var declarations per line
|
3 | * @author Alberto Rodríguez
|
4 | */
|
5 | ;
|
6 |
|
7 | //------------------------------------------------------------------------------
|
8 | // Rule Definition
|
9 | //------------------------------------------------------------------------------
|
10 |
|
11 | module.exports = {
|
12 | meta: {
|
13 | docs: {
|
14 | description: "require or disallow newlines around variable declarations",
|
15 | category: "Stylistic Issues",
|
16 | recommended: false
|
17 | },
|
18 |
|
19 | schema: [
|
20 | {
|
21 | enum: ["always", "initializations"]
|
22 | }
|
23 | ],
|
24 |
|
25 | fixable: "whitespace"
|
26 | },
|
27 |
|
28 | create(context) {
|
29 |
|
30 | const ERROR_MESSAGE = "Expected variable declaration to be on a new line.";
|
31 | const always = context.options[0] === "always";
|
32 |
|
33 | //--------------------------------------------------------------------------
|
34 | // Helpers
|
35 | //--------------------------------------------------------------------------
|
36 |
|
37 |
|
38 | /**
|
39 | * Determine if provided keyword is a variant of for specifiers
|
40 | * @private
|
41 | * @param {string} keyword - keyword to test
|
42 | * @returns {boolean} True if `keyword` is a variant of for specifier
|
43 | */
|
44 | function isForTypeSpecifier(keyword) {
|
45 | return keyword === "ForStatement" || keyword === "ForInStatement" || keyword === "ForOfStatement";
|
46 | }
|
47 |
|
48 | /**
|
49 | * Checks newlines around variable declarations.
|
50 | * @private
|
51 | * @param {ASTNode} node - `VariableDeclaration` node to test
|
52 | * @returns {void}
|
53 | */
|
54 | function checkForNewLine(node) {
|
55 | if (isForTypeSpecifier(node.parent.type)) {
|
56 | return;
|
57 | }
|
58 |
|
59 | const declarations = node.declarations;
|
60 | let prev;
|
61 |
|
62 | declarations.forEach(current => {
|
63 | if (prev && prev.loc.end.line === current.loc.start.line) {
|
64 | if (always || prev.init || current.init) {
|
65 | context.report({
|
66 | node,
|
67 | message: ERROR_MESSAGE,
|
68 | loc: current.loc.start,
|
69 | fix: fixer => fixer.insertTextBefore(current, "\n")
|
70 | });
|
71 | }
|
72 | }
|
73 | prev = current;
|
74 | });
|
75 | }
|
76 |
|
77 | //--------------------------------------------------------------------------
|
78 | // Public
|
79 | //--------------------------------------------------------------------------
|
80 |
|
81 | return {
|
82 | VariableDeclaration: checkForNewLine
|
83 | };
|
84 |
|
85 | }
|
86 | };
|