Files
AIHostingTycoon/packages/shared/src/utils/formatting.ts
T
josh 617b29bd85
CI / build-and-push (push) Successful in 33s
Fix crypto.randomUUID crash on non-HTTPS origins
Replace all crypto.randomUUID() calls with a uuid() utility that
falls back to Math.random-based generation when the Web Crypto API
is unavailable (plain HTTP contexts).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-24 18:50:37 -04:00

44 lines
1.4 KiB
TypeScript

export function formatNumber(n: number): string {
if (n < 0) return `-${formatNumber(-n)}`;
if (n < 1_000) return Math.floor(n).toString();
if (n < 1_000_000) return `${(n / 1_000).toFixed(1)}K`;
if (n < 1_000_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
if (n < 1_000_000_000_000) return `${(n / 1_000_000_000).toFixed(1)}B`;
return `${(n / 1_000_000_000_000).toFixed(1)}T`;
}
export function formatMoney(n: number): string {
if (n < 0) return `-$${formatNumber(-n)}`;
return `$${formatNumber(n)}`;
}
export function formatPercent(n: number, decimals = 1): string {
return `${(n * 100).toFixed(decimals)}%`;
}
export function formatTokens(n: number): string {
return `${formatNumber(n)} tok`;
}
export function formatFlops(n: number): string {
return `${formatNumber(n)} FLOPS`;
}
export function uuid(): string {
if (typeof crypto !== 'undefined' && crypto.randomUUID) {
return crypto.randomUUID();
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
});
}
export function formatDuration(ticks: number): string {
if (ticks < 60) return `${ticks}s`;
if (ticks < 3600) return `${Math.floor(ticks / 60)}m ${ticks % 60}s`;
const hours = Math.floor(ticks / 3600);
const minutes = Math.floor((ticks % 3600) / 60);
return `${hours}h ${minutes}m`;
}