Skip to content

Commit

Permalink
fix #6. change hyphen and space to underscore in ToSnakeCase.
Browse files Browse the repository at this point in the history
  • Loading branch information
huandu committed Jan 6, 2015
1 parent a72ee4c commit 3383fdd
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
21 changes: 14 additions & 7 deletions convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,20 +68,21 @@ func ToCamelCase(str string) string {
// "HTTPServer" => "http_server"
// "NoHTTPS" => "no_https"
// "GO_PATH" => "go_path"
// "GO PATH" => "go_path" // space is converted to underscore.
// "GO-PATH" => "go_path" // hyphen is converted to underscore.
func ToSnakeCase(str string) string {
if len(str) == 0 {
return ""
}

buf := &bytes.Buffer{}
var r0, r1 rune
var prev, r0, r1 rune
var size int

addUnderscore := false // become true if first non-underscore rune is found.
r0 = '_'

for len(str) > 0 {
addUnderscore = addUnderscore || r0 != '_'
prev = r0
r0, size = utf8.DecodeRuneInString(str)
str = str[size:]

Expand All @@ -90,11 +91,10 @@ func ToSnakeCase(str string) string {
buf.WriteByte(byte(str[0]))

case unicode.IsUpper(r0):
if addUnderscore {
if prev != '_' {
buf.WriteRune('_')
}

addUnderscore = true
buf.WriteRune(unicode.ToLower(r0))

if len(str) == 0 {
Expand Down Expand Up @@ -125,25 +125,32 @@ func ToSnakeCase(str string) string {
}

if !unicode.IsUpper(r0) {
if r0 == '_' {
if r0 == '_' || r0 == ' ' || r0 == '-' {
r0 = '_'

buf.WriteRune(unicode.ToLower(r1))
} else {
buf.WriteRune('_')
buf.WriteRune(unicode.ToLower(r1))
buf.WriteRune(r0)
}

break
}

buf.WriteRune(unicode.ToLower(r1))
}

if len(str) == 0 {
if len(str) == 0 || r0 == '_' {
buf.WriteRune(unicode.ToLower(r0))
break
}

default:
if r0 == ' ' || r0 == '-' {
r0 = '_'
}

buf.WriteRune(r0)
}
}
Expand Down
3 changes: 3 additions & 0 deletions convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ func TestToSnakeCase(t *testing.T) {
"HELLO____WORLD": "hello____world",
"TW": "tw",
"_C": "_c",

" sentence case ": "__sentence_case__",
" Mixed-hyphen case _and SENTENCE_case and UPPER-case": "_mixed_hyphen_case__and_sentence_case_and_upper_case",
})
}

Expand Down

0 comments on commit 3383fdd

Please sign in to comment.