1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | module.exports = function(context) {
|
12 |
|
13 | "use strict";
|
14 |
|
15 | var THRESHOLD = context.options[0];
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 | var fns = [];
|
23 |
|
24 |
|
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 |
|
48 | if (node.test) {
|
49 | increaseComplexity(node);
|
50 | }
|
51 | }
|
52 |
|
53 | function increaseLogicalComplexity(node) {
|
54 |
|
55 | if (node.operator === "||") {
|
56 | increaseComplexity(node);
|
57 | }
|
58 | }
|
59 |
|
60 |
|
61 |
|
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 | };
|