-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathStringUtil.ts
More file actions
85 lines (79 loc) · 2.08 KB
/
Copy pathStringUtil.ts
File metadata and controls
85 lines (79 loc) · 2.08 KB
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
/**
* Splits a string by comma.
*
* @param input - String instance to split.
*
* @returns A String array containining the split parts.
*/
export function splitCommaSeparated(input: string): string[] {
return input.split(/\s*,\s*/u);
}
/**
* Sanitizes part of a URL by replacing non-word content with a '-'.
*
* @param urlPart - The URL part to sanitize.
*
* @returns The sanitized output.
*/
export function sanitizeUrlPart(urlPart: string): string {
return urlPart.replaceAll(/\W/gu, '-');
}
/**
* Checks the validity of a file name. A valid name consists of word characters, '-' or '.'.
*
* @param name - The name of the file to validate.
*
* @returns True if the filename is valid, false otherwise.
*/
export function isValidFileName(name: string): boolean {
return /^[\w.-]+$/u.test(name);
}
/**
* Checks whether the given string is a valid URL.
*
* @param url - String to check.
*
* @returns True if the string is a valid URL.
*/
export function isUrl(url: string): boolean {
try {
// eslint-disable-next-line no-new
new URL(url);
return true;
} catch {
return false;
}
}
/**
* Converts milliseconds to an ISO 8601 duration string.
* The only categories used are days, hours, minutes, and seconds,
* because months have no fixed size in milliseconds.
*
* @param ms - The duration in ms to convert.
*/
export function msToDuration(ms: number): string {
let totalSeconds = ms / 1000;
const days = Math.floor(totalSeconds / (60 * 60 * 24));
totalSeconds -= days * 60 * 60 * 24;
const hours = Math.floor(totalSeconds / (60 * 60));
totalSeconds -= hours * 60 * 60;
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds - (minutes * 60);
const stringParts: string[] = [ 'P' ];
if (days > 0) {
stringParts.push(`${days}D`);
}
if (hours > 0 || minutes > 0 || seconds > 0) {
stringParts.push('T');
}
if (hours > 0) {
stringParts.push(`${hours}H`);
}
if (minutes > 0) {
stringParts.push(`${minutes}M`);
}
if (seconds > 0) {
stringParts.push(`${seconds}S`);
}
return stringParts.join('');
}