]> git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/no-undef-init.js
2c2204cf0fe2d27ca7932f932ce5566d0de28fc1
[pve-eslint.git] / eslint / lib / rules / no-undef-init.js
1 /**
2 * @fileoverview Rule to flag when initializing to undefined
3 * @author Ilya Volodin
4 */
5
6 "use strict";
7
8 const astUtils = require("./utils/ast-utils");
9
10 //------------------------------------------------------------------------------
11 // Rule Definition
12 //------------------------------------------------------------------------------
13
14 /** @type {import('../shared/types').Rule} */
15 module.exports = {
16 meta: {
17 type: "suggestion",
18
19 docs: {
20 description: "disallow initializing variables to `undefined`",
21 recommended: false,
22 url: "https://eslint.org/docs/rules/no-undef-init"
23 },
24
25 schema: [],
26 fixable: "code",
27
28 messages: {
29 unnecessaryUndefinedInit: "It's not necessary to initialize '{{name}}' to undefined."
30 }
31 },
32
33 create(context) {
34
35 const sourceCode = context.getSourceCode();
36
37 return {
38
39 VariableDeclarator(node) {
40 const name = sourceCode.getText(node.id),
41 init = node.init && node.init.name,
42 scope = context.getScope(),
43 undefinedVar = astUtils.getVariableByName(scope, "undefined"),
44 shadowed = undefinedVar && undefinedVar.defs.length > 0,
45 lastToken = sourceCode.getLastToken(node);
46
47 if (init === "undefined" && node.parent.kind !== "const" && !shadowed) {
48 context.report({
49 node,
50 messageId: "unnecessaryUndefinedInit",
51 data: { name },
52 fix(fixer) {
53 if (node.parent.kind === "var") {
54 return null;
55 }
56
57 if (node.id.type === "ArrayPattern" || node.id.type === "ObjectPattern") {
58
59 // Don't fix destructuring assignment to `undefined`.
60 return null;
61 }
62
63 if (sourceCode.commentsExistBetween(node.id, lastToken)) {
64 return null;
65 }
66
67 return fixer.removeRange([node.id.range[1], node.range[1]]);
68 }
69 });
70 }
71 }
72 };
73
74 }
75 };