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 | docs: {
|
14 | description: "disallow lexical declarations in case clauses",
|
15 | category: "Best Practices",
|
16 | recommended: true
|
17 | },
|
18 |
|
19 | schema: []
|
20 | },
|
21 |
|
22 | create(context) {
|
23 |
|
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 |
|
41 | return {
|
42 | SwitchCase(node) {
|
43 | for (let i = 0; i < node.consequent.length; i++) {
|
44 | const statement = node.consequent[i];
|
45 |
|
46 | if (isLexicalDeclaration(statement)) {
|
47 | context.report({
|
48 | node,
|
49 | message: "Unexpected lexical declaration in case block."
|
50 | });
|
51 | }
|
52 | }
|
53 | }
|
54 | };
|
55 |
|
56 | }
|
57 | };
|