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