no-case-declarations.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * @fileoverview Rule to flag use of an lexical declarations inside a case clause
  3. * @author Erik Arvidsson
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = {
  10. meta: {
  11. type: "suggestion",
  12. docs: {
  13. description: "disallow lexical declarations in case clauses",
  14. category: "Best Practices",
  15. recommended: true,
  16. url: "https://eslint.org/docs/rules/no-case-declarations"
  17. },
  18. schema: [],
  19. messages: {
  20. unexpected: "Unexpected lexical declaration in case block."
  21. }
  22. },
  23. create(context) {
  24. /**
  25. * Checks whether or not a node is a lexical declaration.
  26. * @param {ASTNode} node A direct child statement of a switch case.
  27. * @returns {boolean} Whether or not the node is a lexical declaration.
  28. */
  29. function isLexicalDeclaration(node) {
  30. switch (node.type) {
  31. case "FunctionDeclaration":
  32. case "ClassDeclaration":
  33. return true;
  34. case "VariableDeclaration":
  35. return node.kind !== "var";
  36. default:
  37. return false;
  38. }
  39. }
  40. return {
  41. SwitchCase(node) {
  42. for (let i = 0; i < node.consequent.length; i++) {
  43. const statement = node.consequent[i];
  44. if (isLexicalDeclaration(statement)) {
  45. context.report({
  46. node: statement,
  47. messageId: "unexpected"
  48. });
  49. }
  50. }
  51. }
  52. };
  53. }
  54. };