All files script-coverage.ts

100% Statements 38/38
100% Branches 18/18
100% Functions 5/5
100% Lines 35/35

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          932x 42x     890x   12343x               50316x 50316x   36209x     890x 890x 12343x 890x       890x   890x 12343x     890x   890x   890x 5303517x 5303517x 5303517x   5303517x 23024x         23024x       890x             90596x 90596x   90596x 209023x 209023x   209023x 23960x 185063x 95805x   89258x       66636x    
import { type Profiler } from "node:inspector";
 
type Normalized = { start: number; end: number; count: number };
 
export function normalize(scriptCoverage: Pick<Profiler.ScriptCoverage, "functions">) {
  if (scriptCoverage.functions.length === 0) {
    return [];
  }
 
  const ranges: (Normalized & { area: number })[] = scriptCoverage.functions
    .flatMap((fn) =>
      fn.ranges.map((range) => ({
        start: range.startOffset,
        end: range.endOffset,
        count: range.count,
        area: range.endOffset - range.startOffset,
      })),
    )
    .sort((a, b) => {
      const diff = b.area - a.area;
      if (diff !== 0) return diff;
 
      return a.end - b.end;
    });
 
  let maxEnd = 0;
  for (const r of ranges) {
    if (r.end > maxEnd) {
      maxEnd = r.end;
    }
  }
 
  const hits = new Uint32Array(maxEnd + 1);
 
  for (const range of ranges) {
    hits.fill(range.count, range.start, range.end + 1);
  }
 
  const normalized: Normalized[] = [];
 
  let start = 0;
 
  for (let end = 1; end <= hits.length; end++) {
    const isLast = end === hits.length;
    const current = isLast ? null : hits[end];
    const previous = hits[start];
 
    if (current !== previous || isLast) {
      normalized.push({
        start,
        end: end - 1,
        count: previous,
      });
      start = end;
    }
  }
 
  return normalized;
}
 
export function getCount(
  offset: Pick<Profiler.CoverageRange, "startOffset" | "endOffset">,
  coverages: Normalized[],
) {
  let low = 0;
  let high = coverages.length - 1;
 
  while (low <= high) {
    const mid = Math.floor((low + high) / 2);
    const coverage = coverages[mid];
 
    if (coverage.start <= offset.startOffset && offset.startOffset <= coverage.end) {
      return coverage.count;
    } else if (offset.startOffset < coverage.start) {
      high = mid - 1;
    } else {
      low = mid + 1;
    }
  }
 
  return 0;
}