-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdisplay.ts
106 lines (97 loc) · 2.43 KB
/
display.ts
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Copyright 2023-present the Deno authors. All rights reserved. MIT license.
import { difference, type Unit } from "std/datetime/difference.ts";
/**
* Returns a pluralized string for the given amount and unit.
*
* @example
* ```ts
* import { pluralize } from "@/utils/display.ts";
*
* pluralize(0, "meow"); // Returns "0 meows"
* pluralize(1, "meow"); // Returns "1 meow"
* ```
*/
export function pluralize(amount: number, unit: string) {
// return amount === 1 ? `${amount} ${unit}` : `${amount} ${unit}s`;
return `${amount} ${unit}`;
}
/**
* Returns how long ago a given date is from now.
*
* @example
* ```ts
* import { timeAgo } from "@/utils/display.ts";
* import { SECOND, MINUTE, HOUR } from "std/datetime/constants.ts";
*
* timeAgo(new Date()); // Returns "just now"
* timeAgo(new Date(Date.now() - 3 * HOUR)); // Returns "3 hours ago"
* ```
*/
export function timeAgo(date: Date) {
const now = new Date();
if (date > now) {
throw new Error("Timestamp must be in the past");
}
const match = Object.entries(
difference(now, date, {
// These units make sense for a web UI
units: [
"seconds",
"minutes",
"hours",
"days",
"weeks",
"months",
"years",
],
}),
)
.toReversed()
.find(([_, amount]) => amount > 0);
if (match === undefined) {
return "şimdi";
}
const [unit, amount] = match;
const unitMapping: Record<Unit, string> = {
milliseconds: "milisaniye",
seconds: "saniye",
minutes: "dakika",
hours: "saat",
days: "gün",
weeks: "hafta",
months: "ay",
quarters: "çeyrek",
years: "yıl",
};
return `${pluralize(amount, unitMapping[<Unit> unit])} önce`;
}
/**
* Returns a formatted string based on the given amount of currency and the
* `en-US` locale. Change the locale for your use case as required.
*
* @see {@linkcode Intl.NumberFormat}
*
* @example
* ```ts
* import { formatCurrency } from "@/utils/display.ts";
*
* formatCurrency(5, "USD"); // Returns "$5"
* ```
*/
export function formatCurrency(
amount: number,
currency: string,
): string {
return new Intl.NumberFormat(
"en-US",
{
style: "currency",
currency,
currencyDisplay: "symbol",
maximumFractionDigits: 0,
},
).format(amount)
// Issue: https://stackoverflow.com/questions/44533919/space-after-symbol-with-js-intl
.replace(/^(\D+)/, "$1")
.replace(/\s+/, "");
}