UNPKG

1.83 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag when initializing to undefined
3 * @author Ilya Volodin
4 */
5
6"use strict";
7
8const astUtils = require("../ast-utils");
9
10//------------------------------------------------------------------------------
11// Rule Definition
12//------------------------------------------------------------------------------
13
14module.exports = {
15 meta: {
16 docs: {
17 description: "disallow initializing variables to `undefined`",
18 category: "Variables",
19 recommended: false
20 },
21
22 schema: [],
23
24 fixable: "code"
25 },
26
27 create(context) {
28
29 const sourceCode = context.getSourceCode();
30
31 return {
32
33 VariableDeclarator(node) {
34 const name = sourceCode.getText(node.id),
35 init = node.init && node.init.name,
36 scope = context.getScope(),
37 undefinedVar = astUtils.getVariableByName(scope, "undefined"),
38 shadowed = undefinedVar && undefinedVar.defs.length > 0;
39
40 if (init === "undefined" && node.parent.kind !== "const" && !shadowed) {
41 context.report({
42 node,
43 message: "It's not necessary to initialize '{{name}}' to undefined.",
44 data: { name },
45 fix(fixer) {
46 if (node.id.type === "ArrayPattern" || node.id.type === "ObjectPattern") {
47
48 // Don't fix destructuring assignment to `undefined`.
49 return null;
50 }
51 return fixer.removeRange([node.id.range[1], node.range[1]]);
52 }
53 });
54 }
55 }
56 };
57
58 }
59};