parent
3de563c3dc
commit
d192385340
10
snake.go
10
snake.go
@ -11,9 +11,17 @@ func ToSnake(s string) string {
|
|||||||
s = strings.Trim(s, " ")
|
s = strings.Trim(s, " ")
|
||||||
n := ""
|
n := ""
|
||||||
for i, v := range s {
|
for i, v := range s {
|
||||||
if i > 0 && v >= 'A' && v <= 'Z' && n[len(n)-1] != '_' {
|
// treat acronyms as words, eg for JSONData -> JSON is a whole word
|
||||||
|
nextIsCapital := false
|
||||||
|
if i + 1 < len(s) {
|
||||||
|
w := s[i+1]
|
||||||
|
nextIsCapital = w >= 'A' && w <= 'Z'
|
||||||
|
}
|
||||||
|
if i > 0 && v >= 'A' && v <= 'Z' && n[len(n)-1] != '_' && !nextIsCapital {
|
||||||
|
// add underscore if next letter is a capital
|
||||||
n += "_" + string(v)
|
n += "_" + string(v)
|
||||||
} else if v == ' ' {
|
} else if v == ' ' {
|
||||||
|
// replace spaces with underscores
|
||||||
n += "_"
|
n += "_"
|
||||||
} else {
|
} else {
|
||||||
n = n + string(v)
|
n = n + string(v)
|
||||||
|
@ -20,6 +20,7 @@ func TestToSnake(t *testing.T) {
|
|||||||
[]string{"manyManyWords", "many_many_words"},
|
[]string{"manyManyWords", "many_many_words"},
|
||||||
[]string{"AnyKind of_string", "any_kind_of_string"},
|
[]string{"AnyKind of_string", "any_kind_of_string"},
|
||||||
[]string{"numbers2and55with000", "numbers_2_and_55_with_000"},
|
[]string{"numbers2and55with000", "numbers_2_and_55_with_000"},
|
||||||
|
[]string{"JSONData", "json_data"},
|
||||||
}
|
}
|
||||||
for _, i := range cases {
|
for _, i := range cases {
|
||||||
in := i[0]
|
in := i[0]
|
||||||
|
Loading…
Reference in New Issue
Block a user