forked from IvanTorresEdge/inflector
-
Notifications
You must be signed in to change notification settings - Fork 1
/
inflector.go
98 lines (74 loc) · 1.69 KB
/
inflector.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
/*
* Inflector Pkg (Go)
*
* Copyright (c) 2013 Ivan Torres
* Released under the MIT license
* https://github.com/mexpolk/inflector/blob/master/LICENSE
*
*/
package inflector
import (
"regexp"
"strings"
)
// Shortcut to strings.ToLower()
func lower(str string) string {
return strings.ToLower(trim(str))
}
// Prepares strings by splitting by caps, spaces, dashes, and underscore
func split(str string) (words []string) {
repl := strings.NewReplacer("-", " ", "_", " ")
rex1 := regexp.MustCompile("([A-Z]+)")
rex2 := regexp.MustCompile("(\\w+)")
str = trim(str)
// Convert dash and underscore to spaces
str = repl.Replace(str)
// Split when uppercase is found (needed for Snake)
str = rex1.ReplaceAllString(str, " $1")
// Get the final list of words
words = rex2.FindAllString(str, -1)
return
}
// Inflects to camelCase
func ToCamel(str string) (out string) {
words := split(str)
out = words[0]
for _, w := range split(str)[1:] {
out += upper(w[:1]) + w[1:]
}
return
}
// Inflects to kebab-case
func ToDash(str string) (out string) {
words := split(str)
for i, w := range words {
words[i] = lower(w)
}
out = strings.Join(words, "-")
return
}
// Inflects to PascalCase
func ToPascal(str string) (out string) {
out = ""
for _, w := range split(str) {
out += upper(w[:1]) + w[1:]
}
return
}
// Inflects to snake_case
func ToUnderscore(str string) (out string) {
words := split(str)
for i, w := range words {
words[i] = lower(w)
}
out = strings.Join(words, "_")
return
}
// Removes leading whitespaces
func trim(str string) string {
return strings.Trim(str, " ")
}
// Shortcut to strings.ToUpper()
func upper(str string) string {
return strings.ToUpper(trim(str))
}