-
Notifications
You must be signed in to change notification settings - Fork 67
/
Common.ts
102 lines (83 loc) 路 2.51 KB
/
Common.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
import {capitalize} from 'lodash';
import Env from './Env';
export const escapeString = (str: string): string => {
// eslint-disable-next-line no-control-regex
return str.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
};
export const isBoolean = (value: string): boolean => value === 'true' || value === 'false';
export const isJson = (str: string) => {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return Number.isNaN(Number(str)) && !isBoolean(str) && true;
};
export const getObjectIncludesText = (object: unknown, text: string = ''): boolean => {
if (!text.length) return false;
const searchTextLower = text.toLowerCase();
const stringSpan = JSON.stringify(object).toLowerCase();
return stringSpan.includes(searchTextLower);
};
export const downloadFile = (data: string, fileName: string): Element => {
const element = document.createElement('a');
const file = new Blob([data]);
element.href = URL.createObjectURL(file);
element.download = fileName;
document.body.appendChild(element);
element.click();
return element;
};
export function singularOrPlural(noun: string, quantity: number) {
if (quantity === 1) return noun;
return `${noun}s`;
}
export function ordinalSuffixOf(i: number) {
const j = i % 10;
const k = i % 100;
if (j === 1 && k !== 11) {
return `${i}st`;
}
if (j === 2 && k !== 12) {
return `${i}nd`;
}
if (j === 3 && k !== 13) {
return `${i}rd`;
}
return `${i}th`;
}
export function getTotalCountFromHeaders(meta: any) {
return Number(meta?.response?.headers.get('x-total-count') || 0);
}
export const getServerBaseUrl = () => {
const {host, protocol} = window.location;
const prefix = Env.get('serverPathPrefix');
return `${protocol}//${host}${prefix}`;
};
export const ToTitle = (str: string) => {
return capitalize(str.replace(/\W/g, ' '));
};
export const getIsValidUrl = (url: string): boolean => {
try {
return !!getParsedURL(url);
} catch (e) {
return false;
}
};
export const getParsedURL = (rawUrl: string): URL => {
if (!!rawUrl && !rawUrl.startsWith('http')) {
return new URL(`http://${rawUrl}`);
}
return new URL(rawUrl);
};
export const withLowPriority =
<T extends (...args: any[]) => any>(fn: T): ((...args: Parameters<T>) => Promise<ReturnType<T>>) =>
(...args: Parameters<T>): Promise<ReturnType<T>> =>
new Promise(resolve => {
setTimeout(() => {
resolve(fn(...args));
}, 0);
});
export const toPercent = (value: number) => {
return `${value * 100}%`;
};