|
1 | 1 | import re |
| 2 | +from typing import List, Callable, Union |
2 | 3 |
|
3 | 4 |
|
4 | 5 | def clean(subject: str) -> str: |
@@ -30,35 +31,60 @@ def clean(subject: str) -> str: |
30 | 31 | return subject |
31 | 32 |
|
32 | 33 |
|
| 34 | +def clean_list(subject: str) -> List[str]: |
| 35 | + return clean(subject).split(" ") |
| 36 | + |
| 37 | + |
| 38 | +def transform(subject: str, transformation: Union[Callable, None], glue=" ") -> str: |
| 39 | + normalized = clean_list(subject) |
| 40 | + words = [] |
| 41 | + for idx, word in enumerate(normalized): |
| 42 | + if transformation: |
| 43 | + w = transformation(idx, word) |
| 44 | + else: |
| 45 | + w = word |
| 46 | + words.append(w) |
| 47 | + |
| 48 | + return glue.join(words) |
| 49 | + |
| 50 | + |
| 51 | +def _camel_transformation(idx: int, word: str) -> str: |
| 52 | + if idx == 0: |
| 53 | + return word |
| 54 | + else: |
| 55 | + return upper_first(word) |
| 56 | + |
| 57 | + |
33 | 58 | def camel(subject: str) -> str: |
34 | 59 | """ |
35 | 60 | Returns string in camelCase |
36 | 61 | """ |
37 | | - normalized_subject = clean(subject) |
38 | | - return re.sub(r" [a-z0-9]", lambda m: m.group(0)[1].upper(), normalized_subject, flags=re.IGNORECASE) |
| 62 | + return transform(subject, _camel_transformation, "") |
| 63 | + |
| 64 | + |
| 65 | +def _pascal_transformation(idx: int, word: str) -> str: |
| 66 | + return upper_first(word) |
39 | 67 |
|
40 | 68 |
|
41 | 69 | def pascal(subject: str) -> str: |
42 | 70 | """ |
43 | 71 | Returns string in PascalCase |
44 | 72 | """ |
45 | | - return upper_first(camel(subject)) |
| 73 | + return transform(subject, _pascal_transformation, "") |
46 | 74 |
|
47 | 75 |
|
48 | 76 | def kebab(subject: str) -> str: |
49 | 77 | """ |
50 | 78 | Returns string in kebab-case |
51 | 79 | """ |
52 | | - normalized_subject = clean(subject) |
53 | | - return re.sub(r"\s", '-', normalized_subject) |
| 80 | + return transform(subject, None, "-") |
54 | 81 |
|
55 | 82 |
|
56 | 83 | def snake(subject: str, upper=False) -> str: |
57 | 84 | """ |
58 | 85 | Returns string in snake_case |
59 | 86 | """ |
60 | | - normalized_subject = clean(subject) |
61 | | - s = re.sub(r"\s", '_', normalized_subject) |
| 87 | + s = transform(subject, None, "_") |
62 | 88 |
|
63 | 89 | if upper: |
64 | 90 | s = s.upper() |
|
0 commit comments