UNPKG

agentsqripts

Version:

Comprehensive static code analysis toolkit for identifying technical debt, security vulnerabilities, performance issues, and code quality problems

68 lines (59 loc) 2.67 kB
/** * @file Cognitive complexity calculator for advanced code maintainability assessment * @description Single responsibility: Calculate cognitive complexity metrics with nesting-aware penalty weighting * * This module implements cognitive complexity calculation, a more sophisticated metric than * cyclomatic complexity that considers the psychological complexity of code for human * comprehension. It applies nesting-based penalty multipliers that reflect the actual * mental overhead developers experience when reading and maintaining nested code structures. * * Design rationale: * - Cognitive complexity better predicts actual code maintainability than cyclomatic complexity * - Nesting-aware penalties reflect real psychological burden of deeply nested code * - Line-by-line analysis enables precise complexity attribution and debugging * - Incremental calculation approach maintains performance for large files * - Comprehensive pattern matching covers all JavaScript complexity contributors * * Cognitive complexity methodology: * - Base complexity starts at 0 (unlike cyclomatic which starts at 1) * - Control structures add 1 + nesting level penalty for psychological overhead * - Logical operators in nested contexts multiply complexity impact * - Function definitions within nested scopes add complexity proportional to depth * - Block nesting tracking maintains accurate penalty calculation throughout analysis * - Conservative nesting level management prevents negative values from parsing errors */ /** * Calculates cognitive complexity (more nuanced than cyclomatic) * @param {string} content - File content * @returns {number} Cognitive complexity score */ function calculateCognitiveComplexity(content) { let complexity = 0; let nestingLevel = 0; const lines = content.split('\n'); lines.forEach(line => { const trimmed = line.trim(); // Increment nesting for blocks if (trimmed.includes('{')) { nestingLevel++; } if (trimmed.includes('}')) { nestingLevel = Math.max(0, nestingLevel - 1); } // Add complexity for control structures if (/\b(if|while|for|switch)\s*\(/.test(trimmed)) { complexity += (1 + nestingLevel); } // Add complexity for logical operators (nested) const logicalOps = (trimmed.match(/&&|\|\|/g) || []).length; complexity += logicalOps * Math.max(1, nestingLevel); // Add complexity for nested functions if (/function\s+\w+|=>\s*{|\w+\s*:\s*function/.test(trimmed)) { complexity += nestingLevel; } }); return complexity; } module.exports = { calculateCognitiveComplexity };