-
Notifications
You must be signed in to change notification settings - Fork 236
Expand file tree
/
Copy pathJavaNames.java
More file actions
48 lines (41 loc) · 1.45 KB
/
JavaNames.java
File metadata and controls
48 lines (41 loc) · 1.45 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
package net.datafaker.internal.helper;
import org.jspecify.annotations.Nullable;
import static java.lang.Character.isLetter;
import static java.lang.Character.toLowerCase;
import static java.lang.Character.toUpperCase;
import static net.datafaker.internal.helper.JavaNames.Transform.SAME;
import static net.datafaker.internal.helper.JavaNames.Transform.TO_LOWER;
import static net.datafaker.internal.helper.JavaNames.Transform.TO_UPPER;
public class JavaNames {
@Nullable
public static String toJavaNames(@Nullable String string, boolean isMethod) {
if (string == null || string.isEmpty()) return string;
int length = string.length();
char[] res = new char[length];
int pos = 0;
Transform next = isMethod ? TO_LOWER : TO_UPPER;
for (int i = 0; i < length; i++) {
char c = string.charAt(i);
if (isLetter(c)) {
res[pos++] = next.transform(c);
next = SAME;
} else if (c == '_') {
next = TO_UPPER;
} else {
res[pos++] = c;
next = SAME;
}
}
return new String(res, 0, pos);
}
enum Transform {
SAME, TO_LOWER, TO_UPPER;
public char transform(char c) {
return switch (this) {
case SAME -> c;
case TO_LOWER -> toLowerCase(c);
case TO_UPPER -> toUpperCase(c);
};
}
}
}