diff options
| author | Fuwn <[email protected]> | 2026-04-28 05:32:28 -0700 |
|---|---|---|
| committer | Fuwn <[email protected]> | 2026-04-28 05:32:28 -0700 |
| commit | ae074b7dfeb2265fcaf2ac69692362b133f4069e (patch) | |
| tree | 18ba0d6057f10ad6919ffbcaa94088276113eb6a /src/lib/Media/Anime/Airing/format.ts | |
| parent | fix(airing): round residual hour and minute in AiringTime component (diff) | |
| download | due.moe-ae074b7dfeb2265fcaf2ac69692362b133f4069e.tar.xz due.moe-ae074b7dfeb2265fcaf2ac69692362b133f4069e.zip | |
refactor(airing): unify countdown formatter into shared helper
Diffstat (limited to 'src/lib/Media/Anime/Airing/format.ts')
| -rw-r--r-- | src/lib/Media/Anime/Airing/format.ts | 61 |
1 files changed, 61 insertions, 0 deletions
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 }; +}; |