lib
Timing & size formatters
formatNs / formatBytes — the display units every Hextor block agrees on.
npx shadcn@latest add @hextor/formatSource
/**
* Display formatters shared by every Hextor block that renders a timing or a
* memory figure. Kept in one place so a benchmark reads identically in the
* report, the result panel and the shared Skill Card — a number that changes
* unit between two views reads as two different measurements.
*
* Pair these with the `tnum` utility from @hextor/tokens: without tabular
* numerals the digits jitter as values stream in.
*/
/** Nanoseconds to the largest unit that keeps the mantissa readable. */
export function formatNs(ns: number): string {
if (ns < 1_000) return `${ns.toFixed(0)} ns`;
if (ns < 1_000_000) return `${(ns / 1_000).toFixed(1)} µs`;
if (ns < 1_000_000_000) return `${(ns / 1_000_000).toFixed(1)} ms`;
return `${(ns / 1_000_000_000).toFixed(2)} s`;
}
/** Bytes in binary units. KB is shown whole — sub-KB precision is noise here. */
export function formatBytes(b: number): string {
if (b < 1024) return `${b} B`;
if (b < 1024 ** 2) return `${(b / 1024).toFixed(0)} KB`;
return `${(b / 1024 ** 2).toFixed(1)} MB`;
}