export const RULE_COUNT_FOLD_THRESHOLD = 5; export type RuleCountRow = { orgType: string | null; place: string | null; }; export type RuleCountCell = { orgType: string | null; place: string | null; count: number; folded: boolean; }; export type RuleLaunchCounts = { finished: number; cells: RuleCountCell[]; }; function normalizePlace(raw: string | null): string { return (raw ?? "").trim().replace(/\s+/g, " ").toLowerCase(); } function cellKey(orgType: string | null, placeKey: string): string { return `${orgType ?? ""}\u0000${placeKey}`; } /** * Finished-Rule counts by group type and place. Any cell under five is folded * so a single group cannot be picked out. */ export function aggregateRuleLaunchCounts(rows: RuleCountRow[]): RuleLaunchCounts { const grouped = new Map< string, { orgType: string | null; place: string | null; count: number } >(); for (const row of rows) { const orgType = row.orgType && row.orgType.trim().length > 0 ? row.orgType : null; const placeRaw = row.place && row.place.trim().length > 0 ? row.place.trim() : null; const key = cellKey(orgType, normalizePlace(placeRaw)); const existing = grouped.get(key); if (existing) { existing.count += 1; } else { grouped.set(key, { orgType, place: placeRaw, count: 1 }); } } const shown: RuleCountCell[] = []; let foldedCount = 0; for (const cell of grouped.values()) { if (cell.count < RULE_COUNT_FOLD_THRESHOLD) { foldedCount += cell.count; continue; } shown.push({ ...cell, folded: false }); } shown.sort((a, b) => b.count - a.count || (a.orgType ?? "").localeCompare(b.orgType ?? "")); if (foldedCount > 0) { shown.push({ orgType: null, place: null, count: foldedCount, folded: true, }); } return { finished: rows.length, cells: shown }; }