UNPKG

2.52 kBJavaScriptView Raw
1/**
2 * @fileoverview Counts the cyclomatic complexity of each function of the script. See http://en.wikipedia.org/wiki/Cyclomatic_complexity.
3 * Counts the number of if, conditional, for, whilte, try, switch/case,
4 * @author Patrick Brosset
5 */
6
7//------------------------------------------------------------------------------
8// Rule Definition
9//------------------------------------------------------------------------------
10
11module.exports = function(context) {
12
13 "use strict";
14
15 var THRESHOLD = context.options[0];
16
17 //--------------------------------------------------------------------------
18 // Helpers
19 //--------------------------------------------------------------------------
20
21 // Using a stack to store complexity (handling nested functions)
22 var fns = [];
23
24 // When parsing a new function, store it in our function stack
25 function startFunction() {
26 fns.push(1);
27 }
28
29 function endFunction(node) {
30 var complexity = fns.pop(), name = "anonymous";
31
32 if (node.id) {
33 name = node.id.name;
34 }
35 if (complexity > THRESHOLD) {
36 context.report(node, "Function '{{name}}' has a complexity of {{complexity}}.", { name: name, complexity: complexity });
37 }
38 }
39
40 function increaseComplexity() {
41 if (fns.length) {
42 fns[fns.length - 1] ++;
43 }
44 }
45
46 function increaseSwitchComplexity(node) {
47 // Avoiding `default`
48 if (node.test) {
49 increaseComplexity(node);
50 }
51 }
52
53 function increaseLogicalComplexity(node) {
54 // Avoiding &&
55 if (node.operator === "||") {
56 increaseComplexity(node);
57 }
58 }
59
60 //--------------------------------------------------------------------------
61 // Public API
62 //--------------------------------------------------------------------------
63
64 return {
65 "FunctionDeclaration": startFunction,
66 "FunctionExpression": startFunction,
67 "FunctionDeclaration:exit": endFunction,
68 "FunctionExpression:exit": endFunction,
69
70 "CatchClause": increaseComplexity,
71 "ConditionalExpression": increaseComplexity,
72 "LogicalExpression": increaseLogicalComplexity,
73 "ForStatement": increaseComplexity,
74 "ForInStatement": increaseComplexity,
75 "IfStatement": increaseComplexity,
76 "SwitchCase": increaseSwitchComplexity,
77 "WhileStatement": increaseComplexity,
78 "DoWhileStatement": increaseComplexity
79 };
80
81};