-
Notifications
You must be signed in to change notification settings - Fork 0
/
str.go
100 lines (92 loc) · 2.05 KB
/
str.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
package dbo
import (
"regexp"
"strings"
)
var uppercaseAcronym = map[string]bool{
"ID": true,
}
var numberSequence = regexp.MustCompile(`([a-zA-Z])(\d+)([a-zA-Z]?)`)
var numberReplacement = []byte(`$1 $2 $3`)
func addWordBoundariesToNumbers(s string) string {
b := []byte(s)
b = numberSequence.ReplaceAll(b, numberReplacement)
return string(b)
}
func toCamelInitCase(s string, initCase bool) string {
s = addWordBoundariesToNumbers(s)
s = strings.Trim(s, " ")
n := ""
capNext := initCase
for _, v := range s {
if v >= 'A' && v <= 'Z' {
n += string(v)
}
if v >= '0' && v <= '9' {
n += string(v)
}
if v >= 'a' && v <= 'z' {
if capNext {
n += strings.ToUpper(string(v))
} else {
n += string(v)
}
}
if v == '_' || v == ' ' || v == '-' || v == '.' {
capNext = true
} else {
capNext = false
}
}
return n
}
// ToCamel converts a string to CamelCase
func ToCamel(s string) string {
if uppercaseAcronym[s] {
s = strings.ToLower(s)
}
return toCamelInitCase(s, true)
}
// ToLowerCamel converts a string to lowerCamelCase
func ToLowerCamel(s string) string {
if s == "" {
return s
}
if uppercaseAcronym[s] {
s = strings.ToLower(s)
}
if r := rune(s[0]); r >= 'A' && r <= 'Z' {
s = strings.ToLower(string(r)) + s[1:]
}
return toCamelInitCase(s, false)
}
func toSnakeCase(s string) string {
delimiter := "_"
s = strings.Trim(s, " ")
n := ""
for i, v := range s {
nextCaseIsChanged := false
if i+1 < len(s) {
next := s[i+1]
vIsCap := v >= 'A' && v <= 'Z'
vIsLow := v >= 'a' && v <= 'z'
nextIsCap := next >= 'A' && next <= 'Z'
nextIsLow := next >= 'a' && next <= 'z'
if (vIsCap && nextIsLow) || (vIsLow && nextIsCap) {
nextCaseIsChanged = true
}
}
if i > 0 && n[len(n)-1] != uint8(delimiter[0]) && nextCaseIsChanged {
if v >= 'A' && v <= 'Z' {
n += string(delimiter) + string(v)
} else if v >= 'a' && v <= 'z' {
n += string(v) + string(delimiter)
}
} else if v == ' ' || v == '-' {
n += string(delimiter)
} else {
n = n + string(v)
}
}
return strings.ToLower(n)
}