This repository has been archived by the owner on Jun 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
casing.go
70 lines (57 loc) · 1.47 KB
/
casing.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
package common
import (
"strings"
"unicode"
)
// ToPascalCase returns a pascal-cased (e.g. SomeValueLikeThis) out of a string
func ToPascalCase(value string) string {
b := strings.Builder{}
var toUpper bool
for i, rune := range value {
// Always upper the first character
if i == 0 {
toUpper = true
}
// Always upper the character after non-letter/non-digit skipping the character
if !unicode.IsLetter(rune) && !unicode.IsDigit(rune) {
toUpper = true
continue
}
// If the flag was set by one of the previous steps
if toUpper {
rune = unicode.ToUpper(rune)
toUpper = false
}
b.WriteRune(rune)
}
return b.String()
}
// ToUnderscoreCase returns a underscore-cased (e.g. some_value_like_this) out of a string
func ToUnderscoreCase(value string) string {
b := strings.Builder{}
var previousUnderscore, previousUppercase bool
for _, rune := range value {
// if it's not allowed character we replace it with underscore without
// duplication of underscores
if !unicode.IsLetter(rune) && !unicode.IsDigit(rune) {
if !previousUnderscore {
b.WriteByte('_')
previousUnderscore = true
}
previousUppercase = false
continue
}
if unicode.IsUpper(rune) {
if !previousUnderscore && !previousUppercase {
b.WriteByte('_')
}
b.WriteRune(unicode.ToLower(rune))
previousUppercase = true
} else {
b.WriteRune(rune)
previousUppercase = false
}
previousUnderscore = false
}
return strings.Trim(b.String(), "_")
}