no-undef-init.js 2.3 KB

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