-
Notifications
You must be signed in to change notification settings - Fork 31
/
mapper.go
33 lines (26 loc) · 915 Bytes
/
mapper.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
package meddler
import (
"strings"
"unicode"
)
// MapperFunc signature. Argument is field name, return value is database column.
type MapperFunc func(in string) string
// Mapper defines the function to transform struct field names into database columns.
// Default is strings.TrimSpace, basically a no-op
var Mapper MapperFunc = strings.TrimSpace
// LowerCase returns a lowercased version of the input string
func LowerCase(in string) string {
return strings.ToLower(in)
}
// SnakeCase returns a snake_cased version of the input string
func SnakeCase(in string) string {
runes := []rune(in)
var out []rune
for i := 0; i < len(runes); i++ {
if i > 0 && (unicode.IsUpper(runes[i]) || unicode.IsNumber(runes[i])) && ((i+1 < len(runes) && unicode.IsLower(runes[i+1])) || unicode.IsLower(runes[i-1])) {
out = append(out, '_')
}
out = append(out, unicode.ToLower(runes[i]))
}
return string(out)
}