Files
orca/src/main/usage/highest-usage-key.ts
T
1a925ed2b9 perf: select highest usage totals without full sorting (#19490)
* perf: select highest usage totals without full sorting

* test(usage): pin first-inserted tie-break contract for highestUsageKey

Document why the strict > and the NaN sort fallback are load-bearing, and
cover the tie/re-set ordering the replaced stable sort guaranteed.

---------

Co-authored-by: m4air <m4air@m4airs-MacBook-Air.local>
Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com>
2026-09-07 23:28:53 -07:00

19 lines
729 B
TypeScript

// Replaces a stable descending sort, so ties must resolve to the first-inserted
// key — hence the strict `>` below rather than `>=`.
export function highestUsageKey(totals: ReadonlyMap<string, number>): string | null {
let bestKey: string | null = null
let bestTotal = Number.NEGATIVE_INFINITY
for (const [key, total] of totals) {
if (Number.isNaN(total)) {
// NaN makes the old comparator inconsistent; defer to it verbatim so a
// corrupt total cannot change which key the summary reports.
return [...totals].sort((left, right) => right[1] - left[1])[0]?.[0] ?? null
}
if (bestKey === null || total > bestTotal) {
bestKey = key
bestTotal = total
}
}
return bestKey
}