da0da1ad7d45672714dfa53e7c2a8f8bd4065fc3
[platform/framework/web/crosswalk-tizen.git] /
1 /**
2  * @fileoverview require default case in switch statements
3  * @author Aliaksei Shytkin
4  */
5 "use strict";
6
7 var COMMENT_VALUE = "no default";
8
9 //------------------------------------------------------------------------------
10 // Rule Definition
11 //------------------------------------------------------------------------------
12
13 module.exports = function(context) {
14
15     //--------------------------------------------------------------------------
16     // Helpers
17     //--------------------------------------------------------------------------
18
19     /**
20      * Shortcut to get last element of array
21      * @param  {*[]} collection Array
22      * @returns {*} Last element
23      */
24     function last(collection) {
25         return collection[collection.length - 1];
26     }
27
28     //--------------------------------------------------------------------------
29     // Public
30     //--------------------------------------------------------------------------
31
32     return {
33
34         "SwitchStatement": function(node) {
35
36             if (!node.cases.length) {
37                 // skip check of empty switch because there is no easy way
38                 // to extract comments inside it now
39                 return;
40             }
41
42             var hasDefault = node.cases.some(function(v) {
43                 return v.test === null;
44             });
45
46             if (!hasDefault) {
47
48                 var comment;
49                 var comments;
50
51                 var lastCase = last(node.cases);
52                 comments = context.getComments(lastCase).trailing;
53
54                 if (comments.length) {
55                     comment = last(comments);
56                 }
57
58                 if (!comment || comment.value.trim() !== COMMENT_VALUE) {
59                     context.report(node, "Expected a default case.");
60                 }
61             }
62         }
63     };
64 };