-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
cgstrings.go
63 lines (58 loc) 路 1.45 KB
/
cgstrings.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
// package cgstrings has various string processing functions that are useful during code generation.
package cgstrings
import (
"strings"
"unicode"
)
// Unhyphenate removes all hyphens from s, then uppercasing the letter following each hyphen.
// For example, "abc-def-ghi" becomes "abcDefGhi".
func Unhyphenate(str string) string {
return ModifyStringAroundDelimeter(str, "-", UppercaseFirst)
}
// Camel converts s to camelCase.
func Camel(s string) string {
if s == "" {
return ""
}
s = Unhyphenate(s)
runes := []rune(s)
res := make([]rune, 0, len(runes))
for i, r := range runes {
if unicode.IsLower(r) {
res = append(res, runes[i:]...)
break
}
res = append(res, unicode.ToLower(r))
}
return string(res)
}
// UppercaseFirst uppercases the first letter of s.
// E.g. "abc" -> "Abc"
func UppercaseFirst(s string) string {
if s == "" {
return ""
}
runes := []rune(s)
runes[0] = unicode.ToUpper(runes[0])
return string(runes)
}
func ModifyStringAroundDelimeter(str, delim string, modifyNext func(next string) string) string {
if delim == "" {
return str
}
i := strings.Index(str, delim)
if i < 0 {
return str
}
nextIdx := i + len(delim)
if nextIdx >= len(str) {
// Nothing left after the delimeter, it's at the end of the string.
return str[:len(str)-len(delim)]
}
prev := str[:nextIdx-1]
next := str[nextIdx:]
if next != "" {
next = modifyNext(next)
}
return prev + ModifyStringAroundDelimeter(next, delim, modifyNext)
}