From ae074b7dfeb2265fcaf2ac69692362b133f4069e Mon Sep 17 00:00:00 2001 From: Fuwn Date: Tue, 28 Apr 2026 05:32:28 -0700 Subject: refactor(airing): unify countdown formatter into shared helper --- src/lib/Media/Anime/Airing/format.ts | 61 ++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/lib/Media/Anime/Airing/format.ts (limited to 'src/lib/Media/Anime/Airing/format.ts') diff --git a/src/lib/Media/Anime/Airing/format.ts b/src/lib/Media/Anime/Airing/format.ts new file mode 100644 index 00000000..5fec3cc8 --- /dev/null +++ b/src/lib/Media/Anime/Airing/format.ts @@ -0,0 +1,61 @@ +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 }; +}; -- cgit v1.2.3