-
Notifications
You must be signed in to change notification settings - Fork 0
/
case.go
102 lines (82 loc) · 2.06 KB
/
case.go
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"math/rand"
"regexp"
"strings"
"unicode"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
type caseOperation int
const (
Lower caseOperation = iota
Upper
)
func getCaseOperation(op caseOperation) func(rune) rune {
switch op {
case Lower:
return func(r rune) rune {
return unicode.ToLower(r)
}
case Upper:
return func(r rune) rune {
return unicode.ToUpper(r)
}
default:
return nil
}
}
func toRandomCase(str string) string {
var builder strings.Builder
for _, char := range str {
r := rand.Intn(2)
builder.WriteString(string(getCaseOperation(caseOperation(r))(char)))
}
return builder.String()
}
func toCamelCase(s string) string {
// Replace spaces with underscores to handle both spaces and underscores uniformly
s = strings.ReplaceAll(s, " ", "_")
words := strings.Split(s, "_")
titleCaser := cases.Title(language.Und)
lowerCaser := cases.Lower(language.Und)
// Capitalize each word except the first one
for i, word := range words {
if i == 0 {
words[i] = lowerCaser.String(word)
} else {
words[i] = titleCaser.String(lowerCaser.String(word))
}
}
return strings.Join(words, "")
}
func toSnakeCase(s string) string {
var result []rune
for i, r := range s {
if unicode.IsUpper(r) {
// Add an underscore before uppercase letters, except at the beginning
if i > 0 && (unicode.IsLower(rune(s[i-1])) || unicode.IsDigit(rune(s[i-1])) || (i < len(s)-1 && unicode.IsLower(rune(s[i+1])))) {
result = append(result, '_')
}
result = append(result, unicode.ToLower(r))
} else if unicode.IsSpace(r) || r == '-' || r == '_' || r == '.' {
if len(result) > 0 && result[len(result)-1] != '_' {
result = append(result, '_')
}
} else {
result = append(result, r)
}
}
snake := string(result)
re := regexp.MustCompile("[^a-zA-Z0-9]+")
snake = re.ReplaceAllString(snake, "_")
snake = strings.ToLower(snake)
snake = strings.Trim(snake, "_")
return snake
}
func toUpper(s string) string {
return strings.ToUpper(s)
}
func toLower(s string) string {
return strings.ToLower(s)
}