1 | /**
|
2 | * @fileoverview require default case in switch statements
|
3 | * @author Aliaksei Shytkin
|
4 | */
|
5 | ;
|
6 |
|
7 | const DEFAULT_COMMENT_PATTERN = /^no default$/i;
|
8 |
|
9 | //------------------------------------------------------------------------------
|
10 | // Rule Definition
|
11 | //------------------------------------------------------------------------------
|
12 |
|
13 | module.exports = {
|
14 | meta: {
|
15 | docs: {
|
16 | description: "require `default` cases in `switch` statements",
|
17 | category: "Best Practices",
|
18 | recommended: false,
|
19 | url: "https://eslint.org/docs/rules/default-case"
|
20 | },
|
21 |
|
22 | schema: [{
|
23 | type: "object",
|
24 | properties: {
|
25 | commentPattern: {
|
26 | type: "string"
|
27 | }
|
28 | },
|
29 | additionalProperties: false
|
30 | }],
|
31 |
|
32 | messages: {
|
33 | missingDefaultCase: "Expected a default case."
|
34 | }
|
35 | },
|
36 |
|
37 | create(context) {
|
38 | const options = context.options[0] || {};
|
39 | const commentPattern = options.commentPattern
|
40 | ? new RegExp(options.commentPattern)
|
41 | : DEFAULT_COMMENT_PATTERN;
|
42 |
|
43 | const sourceCode = context.getSourceCode();
|
44 |
|
45 | //--------------------------------------------------------------------------
|
46 | // Helpers
|
47 | //--------------------------------------------------------------------------
|
48 |
|
49 | /**
|
50 | * Shortcut to get last element of array
|
51 | * @param {*[]} collection Array
|
52 | * @returns {*} Last element
|
53 | */
|
54 | function last(collection) {
|
55 | return collection[collection.length - 1];
|
56 | }
|
57 |
|
58 | //--------------------------------------------------------------------------
|
59 | // Public
|
60 | //--------------------------------------------------------------------------
|
61 |
|
62 | return {
|
63 |
|
64 | SwitchStatement(node) {
|
65 |
|
66 | if (!node.cases.length) {
|
67 |
|
68 | /*
|
69 | * skip check of empty switch because there is no easy way
|
70 | * to extract comments inside it now
|
71 | */
|
72 | return;
|
73 | }
|
74 |
|
75 | const hasDefault = node.cases.some(v => v.test === null);
|
76 |
|
77 | if (!hasDefault) {
|
78 |
|
79 | let comment;
|
80 |
|
81 | const lastCase = last(node.cases);
|
82 | const comments = sourceCode.getCommentsAfter(lastCase);
|
83 |
|
84 | if (comments.length) {
|
85 | comment = last(comments);
|
86 | }
|
87 |
|
88 | if (!comment || !commentPattern.test(comment.value.trim())) {
|
89 | context.report({ node, messageId: "missingDefaultCase" });
|
90 | }
|
91 | }
|
92 | }
|
93 | };
|
94 | }
|
95 | };
|