Cyclomatic complexity

From Horonomos-laps/Yana-AI · View interactive version

Cyclomatic complexity is an AI agent skill from the GitHub repository Horonomos-laps/Yana-AI. Cyclomatic complexity measurement for JavaScript/TypeScript. Function complexity scoring, threshold enforcement, refactor detection, and per-file complexity reports. Sources: marcondescruza/node-complexity (MIT).

How to use this skill

Skill file

/cyclomatic-complexity

When to Use

Do NOT use for


Cyclomatic complexity formula

CC = Edges − Nodes + 2 * ConnectedComponents
   = 1 + (number of decision points)

Decision points: if, else if, ?:, &&, ||, switch case, while, for, for-in, for-of, catch

Thresholds:


Measure with ESLint complexity rule

// eslint.config.js
export default [
  {
    rules: {
      complexity: ['error', { max: 10 }],  // fail if CC > 10
    },
    files: ['src/**/*.{js,ts}'],
  },
]

Manual AST-based complexity scorer

import { parse } from 'acorn'

const DECISION_NODES = new Set([
  'IfStatement', 'ConditionalExpression', 'SwitchCase',
  'WhileStatement', 'DoWhileStatement',
  'ForStatement', 'ForInStatement', 'ForOfStatement',
  'CatchClause',
])
const LOGICAL_OPS = new Set(['&&', '||', '??'])

function measureComplexity(fnSource: string): number {
  const ast = parse(`(${fnSource})`, { ecmaVersion: 2022 })
  let cc = 1

  function walk(node: any) {
    if (!node || typeof node !== 'object') return
    if (DECISION_NODES.has(node.type)) cc++
    if (node.type === 'LogicalExpression' && LOGICAL_OPS.has(node.operator)) cc++
    for (const key of Object.keys(node)) {
      const child = node[key]
      if (Array.isArray(child)) child.forEach(walk)
      else if (child?.type)      walk(child)
    }
  }
  walk(ast)
  return cc
}

console.log(measureComplexity('function f(x) { if (x > 0 && x < 10) return x * 2; return 0 }'))
// → 3 (1 base + 1 if + 1 &&)

File-level complexity report

#!/usr/bin/env bash
# complexity-report.sh — list functions with CC > threshold
THRESHOLD=${1:-10}

npx eslint --format json src/**/*.{js,ts} 2>/dev/null \
  | jq --argjson t "$THRESHOLD" '
      [.[] | .messages[]
       | select(.ruleId == "complexity" and .severity == 2)
       | { file: .filePath? // "?", line: .line, message }
      ] | sort_by(.line)
    '

Cognitive complexity (human readability score)

// Cognitive complexity penalizes nesting more than CC
// Rule: @typescript-eslint/cognitive-complexity
export default [
  {
    plugins: { '@typescript-eslint': tseslint },
    rules: {
      '@typescript-eslint/cognitive-complexity': ['warn', 15],
    },
  },
]

Anti-Fake-Pass Checklist

❌ Measuring CC on minified code → all complexity reported as 1 (single "function")
❌ Ignoring ?? and ?. operators → modern JS complexity undercounted
❌ Threshold too low (≤5) for utility functions → alert fatigue from false positives
❌ Only measuring per-file, not per-function → complex helper buried in a simple file
❌ CC = 1 doesn't mean easy to test — 1 path through deeply nested callbacks is still hard
❌ Skipping CatchClause in walker → error-handling branches missed from score
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.