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