Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 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 | module.exports = { |
| 15 | meta: { |
| 16 | type: "suggestion", |
| 17 | |
| 18 | docs: { |
| 19 | description: "disallow initializing variables to `undefined`", |
| 20 | category: "Variables", |
| 21 | recommended: false, |
| 22 | url: "https://eslint.org/docs/rules/no-undef-init" |
| 23 | }, |
| 24 | |
| 25 | schema: [], |
| 26 | fixable: "code" |
| 27 | }, |
| 28 | |
| 29 | create(context) { |
| 30 | |
| 31 | const sourceCode = context.getSourceCode(); |
| 32 | |
| 33 | return { |
| 34 | |
| 35 | VariableDeclarator(node) { |
| 36 | const name = sourceCode.getText(node.id), |
| 37 | init = node.init && node.init.name, |
| 38 | scope = context.getScope(), |
| 39 | undefinedVar = astUtils.getVariableByName(scope, "undefined"), |
Tim van der Lippe | c8f6ffd | 2020-04-06 13:42:00 +0100 | [diff] [blame^] | 40 | shadowed = undefinedVar && undefinedVar.defs.length > 0, |
| 41 | lastToken = sourceCode.getLastToken(node); |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 42 | |
| 43 | if (init === "undefined" && node.parent.kind !== "const" && !shadowed) { |
| 44 | context.report({ |
| 45 | node, |
| 46 | message: "It's not necessary to initialize '{{name}}' to undefined.", |
| 47 | data: { name }, |
| 48 | fix(fixer) { |
| 49 | if (node.parent.kind === "var") { |
| 50 | return null; |
| 51 | } |
| 52 | |
| 53 | if (node.id.type === "ArrayPattern" || node.id.type === "ObjectPattern") { |
| 54 | |
| 55 | // Don't fix destructuring assignment to `undefined`. |
| 56 | return null; |
| 57 | } |
Tim van der Lippe | c8f6ffd | 2020-04-06 13:42:00 +0100 | [diff] [blame^] | 58 | |
| 59 | if (sourceCode.commentsExistBetween(node.id, lastToken)) { |
| 60 | return null; |
| 61 | } |
| 62 | |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 63 | return fixer.removeRange([node.id.range[1], node.range[1]]); |
| 64 | } |
| 65 | }); |
| 66 | } |
| 67 | } |
| 68 | }; |
| 69 | |
| 70 | } |
| 71 | }; |