game-village-politics-frontend/app/utils/format.ts

27 lines
1.1 KiB
TypeScript
Raw Normal View History

import type { Cost } from '~/types/game'
const pad = (n: number) => String(n).padStart(2, '0')
/** 3725 → "1:02:05" */
export function formatDuration(totalSeconds: number) {
const s = Math.max(0, Math.round(totalSeconds))
return `${Math.floor(s / 3600)}:${pad(Math.floor((s % 3600) / 60))}:${pad(s % 60)}`
}
/** Like formatDuration, with whole days in front once there are any: "3 d 4:05:00". */
export function formatSpan(totalSeconds: number, t: (key: string, values?: Record<string, unknown>) => string) {
const s = Math.max(0, Math.round(totalSeconds))
const days = Math.floor(s / 86400)
return days ? t('time.span_days', { days, time: formatDuration(s % 86400) }) : formatDuration(s)
}
export const formatAmount = (n: number) => String(Math.floor(n))
/** 12.5 → "+12.5", -3 → "-3" */
export const formatRate = (n: number) => `${n >= 0 ? '+' : ''}${Math.round(n * 10) / 10}`
/** A bonus with its sign from the value: 20 → "+20", -50 → "−50", 0 → "0". */
export const formatSigned = (n: number) => `${n > 0 ? '+' : n < 0 ? '−' : ''}${Math.abs(n)}`
export const formatCost = (cost: Cost) => `${cost.wood} / ${cost.clay} / ${cost.iron}`