UNPKG

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