-
Notifications
You must be signed in to change notification settings - Fork 1
/
mod.ts
72 lines (69 loc) · 2.04 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
// Case Style enum
export enum caseStyle {
// eg : LastName
pascalCase = "pascalCase",
// eg : lastName
camelCase = "camelCase",
// eg : last_name
snakeCase = "snakeCase",
// eg : last-name
kebabCase = "kebabCase",
// eg : LAST_NAME
screamingSnakeCase = "screamingSnakeCase",
// eg : LAST-NAME
screamingKebabCase = "screamingKebabCase"
}
const validators = {
pascalCase: /[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]+)*/,
camelCase: /[a-z][a-z0-9]+(?:[A-Z][a-z0-9]+)*/,
snakeCase: /[a-z][a-z0-9]+(?:[_][a-z][a-z0-9]+)*/,
screamingSnakeCase: /[A-Z][A-Z0-9]+(?:[_][A-Z][A-Z0-9]+)*/,
kebabCase: /[a-z][a-z0-9]+(?:[-][a-z][a-z0-9]+)*/,
screamingKebabCase: /[A-Z][A-Z0-9]+(?:[-][A-Z][A-Z0-9]+)*/
};
/**
* Validate the string into the caseStyle wanted
* @param str String to validate
* @param caseStyle caseStyle to validate the string into
*/
export function validate(str: string, style: caseStyle): boolean {
const m = validators[style].exec(str);
return m && m[0] === str;
}
/**
* Format the string into the caseStyle wanted
* @param str String to format
* @param caseStyle caseStyle to format the string into
* TODO (zekth): handle diacritics
*/
export function format(str: string, style: caseStyle): string {
const acc = [];
const reg = /([a-zA-Z0-9À-ž]+)/gm;
str = str.trim().toLowerCase();
const m = str.match(reg);
switch (style) {
case caseStyle.pascalCase:
case caseStyle.camelCase:
for (let i = 0; i < m.length; i++) {
if (
style === caseStyle.pascalCase ||
(style === caseStyle.camelCase && i !== 0)
) {
acc.push(m[i][0].toUpperCase() + m[i].slice(1));
} else {
acc.push(m[i]);
}
}
return acc.join("");
case caseStyle.snakeCase:
return m.join("_");
case caseStyle.kebabCase:
return m.join("-");
case caseStyle.screamingSnakeCase:
return m.join("_").toUpperCase();
case caseStyle.screamingKebabCase:
return m.join("-").toUpperCase();
default:
throw Error("Unknown case style");
}
}