Files
MoShiro/web/shared/format.ts
T
2026-10-04 21:46:39 +08:00

52 lines
2.2 KiB
TypeScript

export function fmtMs(v: number | null | undefined, digits = 1): string {
if (v === null || v === undefined || Number.isNaN(v)) return '—'
if (v >= 1000) return `${(v / 1000).toFixed(2)} s`
return `${v.toFixed(v >= 100 ? 0 : digits)} ms`
}
export function fmtPct(v: number | null | undefined, digits = 2): string {
if (v === null || v === undefined || Number.isNaN(v)) return '—'
return `${v.toFixed(v >= 10 ? 1 : digits)}%`
}
export function fmtMbps(v: number | null | undefined): string {
if (v === null || v === undefined || Number.isNaN(v)) return '—'
return v >= 100 ? `${v.toFixed(0)} Mbit/s` : `${v.toFixed(1)} Mbit/s`
}
export function fmtNum(v: number | null | undefined, digits = 0): string {
if (v === null || v === undefined || Number.isNaN(v)) return '—'
return v.toLocaleString('zh-CN', { maximumFractionDigits: digits })
}
export function fmtTime(iso: string | null | undefined): string {
if (!iso) return '—'
const d = new Date(iso)
return d.toLocaleString('zh-CN', { hour12: false, month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' })
}
export function fmtAgo(iso: string | null | undefined): string {
if (!iso) return '—'
const seconds = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000)
if (seconds < 60) return `${Math.floor(seconds)} 秒前`
if (seconds < 3600) return `${Math.floor(seconds / 60)} 分钟前`
if (seconds < 86400) return `${Math.floor(seconds / 3600)} 小时前`
return `${Math.floor(seconds / 86400)} 天前`
}
export function fmtDuration(ms: number): string {
const s = Math.floor(ms / 1000)
if (s < 60) return `${s} 秒`
if (s < 3600) return `${Math.floor(s / 60)} 分钟`
if (s < 86400) return `${Math.floor(s / 3600)} 小时 ${Math.floor((s % 3600) / 60)} 分钟`
return `${Math.floor(s / 86400)} 天 ${Math.floor((s % 86400) / 3600)} 小时`
}
/** 评分 → 状态色(和后端模型的分档一致:≥85 好,≥60 一般,其余差)。 */
export function scoreTone(score: number | null | undefined): 'ok' | 'warn' | 'bad' | '' {
if (score === null || score === undefined) return ''
if (score >= 85) return 'ok'
if (score >= 60) return 'warn'
return 'bad'
}