All files metrics.ts

100% Statements 57/57
100% Branches 23/23
100% Functions 2/2
100% Lines 53/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157              154x                                       35x 35x 35x 35x   1x 1x     24x 24x   9x 9x   184x 184x             5x                 9x 9x 9x 32x 9x     1555x     154x 154x     4x                                             138x 138x       390x 390x   152x 152x   80x 80x   1481x   138x   138x 138x 138x 138x 138x 443x   138x 138x 138x 138x     138x 138x 138x   138x                     141x 141x 141x       141x       132x 132x      
import * as ts from 'typescript';
 
import { getLineAndCharacter } from './utils.js';
 
import type { HalsteadMetrics, Metrics } from './types.js';
 
export function collectMetrics(rootNode: ts.Node): Metrics {
  const metrics: Metrics = {
    complexity: 1,
    maxBranchDepth: 0,
    maxLoopDepth: 0,
    returns: 0,
    awaits: 0,
    calls: 0,
    loops: 0,
  };
 
  const visit = (node: ts.Node, branchDepth: number, loopDepth: number): void => {
    switch (node.kind) {
      case ts.SyntaxKind.IfStatement:
      case ts.SyntaxKind.WhileStatement:
      case ts.SyntaxKind.DoStatement:
      case ts.SyntaxKind.ForStatement:
      case ts.SyntaxKind.ForInStatement:
      case ts.SyntaxKind.ForOfStatement:
      case ts.SyntaxKind.SwitchStatement:
      case ts.SyntaxKind.CatchClause:
        metrics.complexity += 1;
        branchDepth += 1;
        metrics.maxBranchDepth = Math.max(metrics.maxBranchDepth, branchDepth);
        break;
      case ts.SyntaxKind.ConditionalExpression:
        metrics.complexity += 1;
        break;
      case ts.SyntaxKind.ReturnStatement:
      case ts.SyntaxKind.ThrowStatement:
        metrics.returns += 1;
        break;
      case ts.SyntaxKind.AwaitExpression:
        metrics.awaits += 1;
        break;
      case ts.SyntaxKind.CallExpression:
        metrics.calls += 1;
        break;
      default:
        if (
          node.kind === ts.SyntaxKind.BinaryExpression &&
          ((node as ts.BinaryExpression).operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ||
            (node as ts.BinaryExpression).operatorToken.kind === ts.SyntaxKind.BarBarToken)
        ) {
          metrics.complexity += 1;
        }
    }
 
    if (
      node.kind === ts.SyntaxKind.ForStatement ||
      node.kind === ts.SyntaxKind.ForInStatement ||
      node.kind === ts.SyntaxKind.ForOfStatement
    ) {
      const nextLoopDepth = loopDepth + 1;
      metrics.loops += 1;
      metrics.maxLoopDepth = Math.max(metrics.maxLoopDepth, nextLoopDepth);
      ts.forEachChild(node, (child) => visit(child, branchDepth, nextLoopDepth));
      return;
    }
 
    ts.forEachChild(node, (child) => visit(child, branchDepth, loopDepth));
  };
 
  visit(rootNode, 0, 0);
  return metrics;
}
 
const HALSTEAD_OPERATOR_KINDS = new Set([
  ts.SyntaxKind.PlusToken, ts.SyntaxKind.MinusToken, ts.SyntaxKind.AsteriskToken,
  ts.SyntaxKind.SlashToken, ts.SyntaxKind.PercentToken, ts.SyntaxKind.AsteriskAsteriskToken,
  ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken,
  ts.SyntaxKind.EqualsToken, ts.SyntaxKind.PlusEqualsToken, ts.SyntaxKind.MinusEqualsToken,
  ts.SyntaxKind.AsteriskEqualsToken, ts.SyntaxKind.SlashEqualsToken,
  ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.EqualsEqualsEqualsToken,
  ts.SyntaxKind.ExclamationEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken,
  ts.SyntaxKind.LessThanToken, ts.SyntaxKind.GreaterThanToken,
  ts.SyntaxKind.LessThanEqualsToken, ts.SyntaxKind.GreaterThanEqualsToken,
  ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken,
  ts.SyntaxKind.ExclamationToken, ts.SyntaxKind.QuestionQuestionToken,
  ts.SyntaxKind.IfKeyword, ts.SyntaxKind.ElseKeyword,
  ts.SyntaxKind.ForKeyword, ts.SyntaxKind.WhileKeyword, ts.SyntaxKind.DoKeyword,
  ts.SyntaxKind.SwitchKeyword, ts.SyntaxKind.CaseKeyword,
  ts.SyntaxKind.ReturnKeyword, ts.SyntaxKind.ThrowKeyword,
  ts.SyntaxKind.NewKeyword, ts.SyntaxKind.DeleteKeyword, ts.SyntaxKind.TypeOfKeyword,
  ts.SyntaxKind.AwaitKeyword, ts.SyntaxKind.YieldKeyword,
  ts.SyntaxKind.DotToken, ts.SyntaxKind.OpenParenToken, ts.SyntaxKind.OpenBracketToken,
  ts.SyntaxKind.EqualsGreaterThanToken, ts.SyntaxKind.DotDotDotToken,
]);
 
export function computeHalstead(node: ts.Node): HalsteadMetrics {
  const operatorBag = new Map<string, number>();
  const operandBag = new Map<string, number>();
 
  const walk = (n: ts.Node): void => {
    if (ts.isIdentifier(n) || ts.isPrivateIdentifier(n)) {
      const text = n.text;
      operandBag.set(text, (operandBag.get(text) || 0) + 1);
    } else if (ts.isNumericLiteral(n) || ts.isStringLiteral(n) || ts.isNoSubstitutionTemplateLiteral(n)) {
      const text = n.getText();
      operandBag.set(text, (operandBag.get(text) || 0) + 1);
    } else if (ts.isToken(n) && HALSTEAD_OPERATOR_KINDS.has(n.kind)) {
      const key = ts.SyntaxKind[n.kind];
      operatorBag.set(key, (operatorBag.get(key) || 0) + 1);
    }
    ts.forEachChild(n, walk);
  };
  walk(node);
 
  const distinctOperators = operatorBag.size;
  const distinctOperands = operandBag.size;
  let operators = 0;
  for (const v of operatorBag.values()) operators += v;
  let operands = 0;
  for (const v of operandBag.values()) operands += v;
 
  const vocabulary = distinctOperators + distinctOperands;
  const length = operators + operands;
  const volume = vocabulary > 0 ? length * Math.log2(vocabulary) : 0;
  const difficulty = distinctOperands > 0
    ? (distinctOperators / 2) * (operands / distinctOperands)
    : 0;
  const effort = volume * difficulty;
  const time = effort / 18;
  const estimatedBugs = volume / 3000;
 
  return {
    operators, operands, distinctOperators, distinctOperands,
    vocabulary, length, volume, difficulty, effort, time, estimatedBugs,
  };
}
 
export function computeMaintainabilityIndex(
  halsteadVolume: number,
  cyclomaticComplexity: number,
  linesOfCode: number,
): number {
  const safeVolume = Math.max(halsteadVolume, 1);
  const safeLOC = Math.max(linesOfCode, 1);
  const raw = 171
    - 5.2 * Math.log(safeVolume)
    - 0.23 * cyclomaticComplexity
    - 16.2 * Math.log(safeLOC);
  return Math.max(0, raw * 100 / 171);
}
 
export function countLinesInNode(sourceFile: ts.SourceFile, node: ts.Node): number {
  const loc = getLineAndCharacter(sourceFile, node);
  return Math.max(1, loc.lineEnd - loc.lineStart + 1);
}