-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
132 lines (120 loc) · 2.6 KB
/
index.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import dayjs from "dayjs";
import relativetime from "dayjs/plugin/relativeTime";
/**
* Get status color
* @param status
* @returns string
*/
export function getStatusBadge(status: string): string {
if (
status === "failed" ||
status === "error" ||
status === "rejected" ||
status === "inactive" ||
status === "deactivated"
) {
return "badge-danger";
} else if (
status === "successful" ||
status === "success" ||
status === "completed" ||
status === "complete" ||
status === "paid" ||
status === "approved" ||
status === "active" ||
status === "activated"
) {
return "badge-success";
} else if (status === "neutral") {
return "badge-info";
} else {
return "badge-default";
}
}
/**
* Format date
* @param date
* @param format?
* @returns string
*/
export function formatDate(
date: string | number | Date,
format: string = "DD/MM/YYYY"
): string {
return dayjs(date).format(format);
}
/**
* Check if date is in future
* @param date
* @returns boolean
*/
export function isDateInFuture(date: string | number | Date): boolean {
return dayjs(date).isAfter(dayjs());
}
/**
* Check if the date is today
* @param string
* @returns boolean
*/
export function isDateToday(date: string | number | Date): boolean {
return dayjs(date).isSame(dayjs(), "day");
}
/**
* Show relative time
* @param date
* @param format?
* @returns string
*/
export function showRelativeTime(
date: string | number | Date,
format: string = "DD/MM/YYYY"
): string {
dayjs.extend(relativetime);
return dayjs(date).isAfter(dayjs().subtract(7, "day"))
? dayjs(date).fromNow()
: dayjs(date).format(format);
}
/**
* Capitalize first letter
*/
export function capitalizeFirstLetter(string: string): string {
return string?.charAt(0)?.toUpperCase() + string?.slice(1);
}
/**
* Truncate string
*/
export function truncateString(str: string, num: number): string {
if (str === null || str === undefined || str === "") {
return "";
}
if (str.length <= num) {
return str;
}
return str.slice(0, num) + "...";
}
/**
* Group array of objects by key
*/
export function groupBy<T>(array: any[], callback: (item: T) => string) {
return array.reduce((acc, item) => {
const key = callback(item);
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(item);
return acc as T;
}, {});
}
/**
* Format currency
*/
export function formatCurrency(
amount: number,
currency: string = "USD",
locale: string = "en-US"
): string {
return new Intl.NumberFormat(locale, {
style: "currency",
currency
}).format(amount);
}