aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Media/Anime/Airing/format.ts
blob: 5fec3cc830819f136ba8c5d7e5aef5264224312a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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 };
};