import settings from "$stores/settings"; import { get } from "svelte/store"; type Options = { forceDays?: boolean; }; type Result = { text: string; few: boolean; }; const plural = (value: number, short: boolean, longUnit: string, shortUnit: string) => `${value}${short ? shortUnit : ` ${longUnit}`}${value === 1 || short ? "" : "s"}`; export const formatCountdown = ( secondsUntil: number, options: Options = {}, ): Result => { const short = get(settings).displayShortCountdown; const minutes = Math.round(secondsUntil / 60); if (minutes <= 60) return { text: plural(minutes, short, "minute", "m"), few: true }; const hours = minutes / 60; if (hours <= 24) { const displayHours = Math.floor(minutes / 60); const residualMinutes = minutes % 60; let text = plural(displayHours, short, "hour", "h"); if (residualMinutes > 0) text += `${short ? "" : " "}${plural(residualMinutes, short, "minute", "m")}`; return { text, few: true }; } const totalHours = Math.round(hours); const days = Math.floor(totalHours / 24); const residualHours = totalHours % 24; const weeks = Math.floor(days / 7); const residualDays = days % 7; let text: string; if (weeks >= 2 && !options.forceDays) { text = plural(weeks, short, "week", "w"); if (residualDays > 0) text += `${short ? "" : " "}${plural(residualDays, short, "day", "d")}`; } else { text = plural(days, short, "day", "d"); } if (residualHours > 0) text += `${short ? "" : " "}${plural(residualHours, short, "hour", "h")}`; return { text, few: false }; };