-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxcase.go
80 lines (66 loc) · 1.73 KB
/
xcase.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
package scs
import (
"strings"
"unicode"
)
// The getChunks clears the string of special characters and splits the
// string by whitespace and returns a list of words ignoring empty elements.
func getChunks(s string) []string {
chunks := make([]string, 0, strings.Count(s, " ")+1)
var builder strings.Builder
builder.Grow(len(s))
for _, r := range strings.ToLower(s) {
if unicode.IsLetter(r) || unicode.IsNumber(r) {
builder.WriteRune(r)
} else if builder.Len() > 0 {
chunks = append(chunks, builder.String())
builder.Reset()
}
}
if builder.Len() > 0 {
chunks = append(chunks, builder.String())
}
return chunks
}
// The toUnited converts a string to a format similar to camel or PascalCase.
func toUnited(s string, firstWordIsLower bool) string {
chunks := getChunks(s)
if len(chunks) == 0 {
return ""
}
var builder strings.Builder
builder.Grow(len(s))
// Перше слово
if firstWordIsLower {
builder.WriteString(chunks[0])
} else if v, ok := abbreviations[chunks[0]]; ok {
builder.WriteString(v)
} else {
builder.WriteString(strings.Title(chunks[0]))
}
// Решта слів
for _, chunk := range chunks[1:] {
if v, ok := abbreviations[chunk]; ok {
builder.WriteString(v)
} else {
builder.WriteString(strings.Title(chunk))
}
}
return builder.String()
}
// The toSeparate converts a string to a format similar to snake or kebab-case.
func toSeparate(s, delimiter string) string {
chunks := getChunks(s)
if len(chunks) == 0 {
return ""
}
var builder strings.Builder
totalLen := len(s) + len(chunks) - 1
builder.Grow(totalLen)
builder.WriteString(chunks[0])
for _, chunk := range chunks[1:] {
builder.WriteString(delimiter)
builder.WriteString(chunk)
}
return builder.String()
}