Add SnakeCase

This commit is contained in:
Patrick O'brien 2016-08-08 09:34:11 +10:00
parent c533c90aed
commit 15ea874a75
3 changed files with 48 additions and 1 deletions
strmangle

View file

@ -9,6 +9,7 @@ import (
"math"
"regexp"
"strings"
"unicode"
"github.com/jinzhu/inflection"
)
@ -138,6 +139,22 @@ func CamelCase(name string) string {
return strings.Join(splits, "")
}
// SnakeCase converts TitleCase variable names to snake_case format.
func SnakeCase(name string) string {
runes := []rune(name)
length := len(runes)
var out []rune
for i := 0; i < length; i++ {
if i > 0 && unicode.IsUpper(runes[i]) && ((i+1 < length && unicode.IsLower(runes[i+1])) || unicode.IsLower(runes[i-1]) || unicode.IsDigit(runes[i-1])) {
out = append(out, '_')
}
out = append(out, unicode.ToLower(runes[i]))
}
return string(out)
}
// MakeStringMap converts a map[string]string into the format:
// "key": "value", "key": "value"
func MakeStringMap(types map[string]string) string {