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 | url: "https://eslint.org/docs/rules/one-var-declaration-per-line"
|
18 | },
|
19 |
|
20 | schema: [
|
21 | {
|
22 | enum: ["always", "initializations"]
|
23 | }
|
24 | ],
|
25 |
|
26 | fixable: "whitespace"
|
27 | },
|
28 |
|
29 | create(context) {
|
30 |
|
31 | const ERROR_MESSAGE = "Expected variable declaration to be on a new line.";
|
32 | const always = context.options[0] === "always";
|
33 |
|
34 | //--------------------------------------------------------------------------
|
35 | // Helpers
|
36 | //--------------------------------------------------------------------------
|
37 |
|
38 |
|
39 | /**
|
40 | * Determine if provided keyword is a variant of for specifiers
|
41 | * @private
|
42 | * @param {string} keyword - keyword to test
|
43 | * @returns {boolean} True if `keyword` is a variant of for specifier
|
44 | */
|
45 | function isForTypeSpecifier(keyword) {
|
46 | return keyword === "ForStatement" || keyword === "ForInStatement" || keyword === "ForOfStatement";
|
47 | }
|
48 |
|
49 | /**
|
50 | * Checks newlines around variable declarations.
|
51 | * @private
|
52 | * @param {ASTNode} node - `VariableDeclaration` node to test
|
53 | * @returns {void}
|
54 | */
|
55 | function checkForNewLine(node) {
|
56 | if (isForTypeSpecifier(node.parent.type)) {
|
57 | return;
|
58 | }
|
59 |
|
60 | const declarations = node.declarations;
|
61 | let prev;
|
62 |
|
63 | declarations.forEach(current => {
|
64 | if (prev && prev.loc.end.line === current.loc.start.line) {
|
65 | if (always || prev.init || current.init) {
|
66 | context.report({
|
67 | node,
|
68 | message: ERROR_MESSAGE,
|
69 | loc: current.loc.start,
|
70 | fix: fixer => fixer.insertTextBefore(current, "\n")
|
71 | });
|
72 | }
|
73 | }
|
74 | prev = current;
|
75 | });
|
76 | }
|
77 |
|
78 | //--------------------------------------------------------------------------
|
79 | // Public
|
80 | //--------------------------------------------------------------------------
|
81 |
|
82 | return {
|
83 | VariableDeclaration: checkForNewLine
|
84 | };
|
85 |
|
86 | }
|
87 | };
|