UNPKG

2.83 kBJavaScriptView Raw
1/**
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
13module.exports = {
14 meta: {
15 type: "suggestion",
16
17 docs: {
18 description: "require `default` cases in `switch` statements",
19 category: "Best Practices",
20 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
53 * @param {*[]} collection Array
54 * @returns {*} Last element
55 */
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};