-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmod.ts
80 lines (67 loc) · 1.88 KB
/
mod.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
function preserveCamelCase(input: string | string[]) {
let isLastCharLower = false;
let isLastCharUpper = false;
let isLastLastCharUpper = false;
for (let i = 0; i < input.length; i++) {
const c = input[i];
if (isLastCharLower && /[a-zA-Z]/.test(c) && c.toUpperCase() === c) {
input = input.slice(0, i) + "-" + input.slice(i);
isLastCharLower = false;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = true;
i++;
} else if (
isLastCharUpper &&
isLastLastCharUpper &&
/[a-zA-Z]/.test(c) &&
c.toLowerCase() === c
) {
input = input.slice(0, i - 1) + "-" + input.slice(i - 1);
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = false;
isLastCharLower = true;
} else {
isLastCharLower = c.toLowerCase() === c;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = c.toUpperCase() === c;
}
}
return input;
}
export interface CamelCaseOptions {
pascalCase: boolean;
}
export function camelCase(
input: string | string[],
options: CamelCaseOptions = { pascalCase: false }
) {
function postProcess(x: string) {
return options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x;
}
if (Array.isArray(input)) {
input = input
.map(x => x.trim())
.filter(x => x.length)
.join("-");
} else {
input = input.trim();
}
if (input.length === 0) {
return "";
}
if (input.length === 1) {
return options.pascalCase ? input.toUpperCase() : input.toLowerCase();
}
if (/^[a-z\d]+$/.test(input)) {
return postProcess(input);
}
const hasUpperCase = input !== input.toLowerCase();
if (hasUpperCase) {
input = preserveCamelCase(input);
}
input = (input as string)
.replace(/^[_.\- ]+/, "")
.toLowerCase()
.replace(/[_.\- ]+(\w|$)/g, (m, p1) => p1.toUpperCase());
return postProcess(input);
}