2 * @fileoverview A rule to ensure the use of a single variable declaration.
3 * @author Ian Christian Myers
4 * @copyright 2015 Danny Fritz. All rights reserved.
5 * @copyright 2013 Ian Christian Myers. All rights reserved.
10 //------------------------------------------------------------------------------
12 //------------------------------------------------------------------------------
14 module.exports = function(context) {
16 var MODE = context.options[0] || "always";
18 //--------------------------------------------------------------------------
20 //--------------------------------------------------------------------------
22 var functionStack = [];
25 * Increments the functionStack counter.
29 function startFunction() {
30 functionStack.push(false);
34 * Decrements the functionStack counter.
38 function endFunction() {
43 * Determines if there is more than one var statement in the current scope.
44 * @returns {boolean} Returns true if it is the first var declaration, false if not.
47 function hasOnlyOneVar() {
48 if (functionStack[functionStack.length - 1]) {
51 functionStack[functionStack.length - 1] = true;
56 //--------------------------------------------------------------------------
58 //--------------------------------------------------------------------------
61 "Program": startFunction,
62 "FunctionDeclaration": startFunction,
63 "FunctionExpression": startFunction,
64 "ArrowFunctionExpression": startFunction,
66 "VariableDeclaration": function(node) {
67 var declarationCount = node.declarations.length;
68 if (MODE === "never") {
69 if (declarationCount > 1) {
70 context.report(node, "Split 'var' declaration into multiple statements.");
73 if (hasOnlyOneVar()) {
74 context.report(node, "Combine this with the previous 'var' statement.");
79 "Program:exit": endFunction,
80 "FunctionDeclaration:exit": endFunction,
81 "FunctionExpression:exit": endFunction,
82 "ArrowFunctionExpression:exit": endFunction