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 84 85 86 87 88              921x 40x     881x   10280x               40574x 40574x   28995x     881x 881x 10280x 881x       881x   881x 10280x     881x   881x   881x 4259938x 4259938x 4259938x   4259938x 18977x         18977x       881x             6071x 6071x   6071x 11007x 11007x   11007x       5859x 5148x 2883x   2265x       212x    
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;
}