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