Cyclomatic Complexity
Counts the number of independent execution paths through a function.
Formula
Where decision points are: if, while, do…while, for, for…in, for…of, switch case, catch, ternary expression, and binary && / || / ??.
What it measures
Cyclomatic Complexity (CC), introduced by Thomas McCabe in 1976, quantifies the structural complexity of a function by counting its independent execution paths. A function with no branching has CC = 1. Every additional decision point adds one more path.
Higher CC correlates with increased testing effort (you need at least as many test cases as CC to achieve full branch coverage) and higher likelihood of bugs.
How it's calculated in tsmetrics
tsmetrics walks the tree-sitter AST of the function body and counts these node kinds:
if_statement— +1 perif(theelsebranch is not counted — it's the complement, not a new path)while_statement,do_statement— +1for_statement,for_in_statement— +1switch_case— +1 percaselabelcatch_clause— +1ternary_expression— +1binary_expressionwith operator&&,||, or??— +1
Nested functions are not counted in the enclosing function — each function is its own unit.
TypeScript example
function classify(score: number): string { // CC = 1 if (score >= 90) { // +1 → CC = 2 return "A"; } else if (score >= 80) { // +1 → CC = 3 return "B"; } else if (score >= 70) { // +1 → CC = 4 return "C"; } return score >= 60 ? "D" : "F"; // +1 (ternary) → CC = 5 }
Expected output
Thresholds
| Severity | Condition | Default value |
|---|---|---|
| OK | CC < 10 | — |
| Warning | CC ≥ 10 | 10 |
| Error | CC ≥ 25 | 25 |
Configuration
References
- McCabe, T. J. (1976). A Complexity Measure. IEEE Transactions on Software Engineering, 2(4), 308–320.
- Lanza, M. & Marinescu, R. (2006). Object-Oriented Metrics in Practice. Springer.
Related metrics
Halstead Volume · Maintainability Index · WMC · Brain Method
Edit on GitHub