Files
linux-cloud-router/web/src/format.ts
T

32 lines
1.0 KiB
TypeScript

/** A time of the server in the browser's format, or a dash. */
export function when(time: string | null | undefined) {
return time ? new Date(time).toLocaleString() : '-'
}
/** A value as text: lists joined with commas, an empty value as a dash. */
export function text(value: unknown): string {
if (Array.isArray(value)) {
return value.length === 0 ? '-' : value.join(', ')
}
return value === undefined || value === null || value === '' ? '-' : String(value)
}
/** Seconds as "1h 2m 3s". */
export function duration(seconds: number) {
const h = Math.floor(seconds / 3600)
const m = Math.floor((seconds % 3600) / 60)
return [h && `${h}h`, (h || m) && `${m}m`, `${seconds % 60}s`].filter(Boolean).join(' ')
}
/** Bytes in B, KiB, MiB or GiB. */
export function bytes(count: number) {
const units = ['B', 'KiB', 'MiB', 'GiB']
let value = count
let unit = 0
while (value >= 1024 && unit < units.length - 1) {
value /= 1024
unit += 1
}
return `${unit === 0 ? value : value.toFixed(1)} ${units[unit]}`
}