Skip to content

Instantly share code, notes, and snippets.

@hxsf
Last active April 21, 2022 07:22
Show Gist options
  • Save hxsf/7f5392c0153d3a8607c42eefed02b8cd to your computer and use it in GitHub Desktop.
Save hxsf/7f5392c0153d3a8607c42eefed02b8cd to your computer and use it in GitHub Desktop.
Golang to snake_case
MIT License
Copyright (c) [2021] [hxsf]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
package utils
import (
"strings"
"unicode"
)
func ToSnakeCase(s string) string {
if s == "" {
return s
}
if len(s) == 1 {
return strings.ToLower(s)
}
source := []rune(s)
dist := strings.Builder{}
dist.Grow(len(s) + len(s)/3) // avoid reallocation memory, 33% ~ 50% is recommended
skipNext := false
for i := 0; i < len(source); i++ {
cur := source[i]
switch cur {
case '-', '_':
dist.WriteRune('_')
skipNext = true
continue
}
if unicode.IsLower(cur) || unicode.IsDigit(cur) {
dist.WriteRune(cur)
continue
}
if i == 0 {
dist.WriteRune(unicode.ToLower(cur))
continue
}
last := source[i-1]
if (!unicode.IsLetter(last)) || unicode.IsLower(last) {
if skipNext {
skipNext=false
} else {
dist.WriteRune('_')
}
dist.WriteRune(unicode.ToLower(cur))
continue
}
// last is upper case
if i < len(source) - 1 {
next:= source[i+1]
if unicode.IsLower(next) {
if skipNext {
skipNext=false
} else {
dist.WriteRune('_')
}
dist.WriteRune(unicode.ToLower(cur))
continue
}
}
dist.WriteRune(unicode.ToLower(cur))
}
return dist.String()
}
package utils
import (
"regexp"
"strings"
"testing"
"unicode"
)
var cases = []struct {
args string
want string
}{
{"", ""},
{"camelCase", "camel_case"},
{"PascalCase", "pascal_case"},
{"snake_case", "snake_case"},
{"Pascal_Snake", "pascal_snake"},
{"SCREAMING_SNAKE", "screaming_snake"},
{"kebab-case", "kebab_case"},
{"Pascal-Kebab", "pascal_kebab"},
{"SCREAMING-KEBAB", "screaming_kebab"},
{"A", "a"},
{"AA", "aa"},
{"AAA", "aaa"},
{"AAAA", "aaaa"},
{"AaAa", "aa_aa"},
{"HTTPRequest", "http_request"},
{"BatteryLifeValue", "battery_life_value"},
{"Id0Value", "id0_value"},
{"ID0Value", "id0_value"},
{"MyLIFEIsAwesomE", "my_life_is_awesom_e"},
{"Japan125Canada130Australia150", "japan125_canada130_australia150"},
}
func TestToSnakeCase(t *testing.T) {
for _, tt := range cases {
t.Run("ToSnakeCase: "+tt.args, func(t *testing.T) {
if got := ToSnakeCase(tt.args); got != tt.want {
t.Errorf("ToSnakeCase(%#q) = %#q, want %#q", tt.args, got, tt.want)
}
})
}
}
func BenchmarkCaseByCase(b *testing.B) {
for _, item := range cases {
arg := item.args
b.Run(arg, func(b *testing.B) {
b.Run("ToSnakeCaseRegex", func(b *testing.B) {
for i := 0; i < b.N; i++ {
ToSnakeCaseRegex(arg)
}
})
b.Run("ToSnakeCaseByJensSkipr", func(b *testing.B) {
for i := 0; i < b.N; i++ {
ToSnakeCaseByJensSkipr(arg)
}
})
b.Run("ToSnakeCase", func(b *testing.B) {
for i := 0; i < b.N; i++ {
ToSnakeCase(arg)
}
})
})
}
}
func BenchmarkOneCase(b *testing.B) {
b.Run("ToSnakeCaseRegex", func(b *testing.B) {
for i := 0; i < b.N; i++ {
ToSnakeCaseRegex("BatteryLifeValue")
}
})
b.Run("ToSnakeCaseByJensSkipr", func(b *testing.B) {
for i := 0; i < b.N; i++ {
ToSnakeCaseByJensSkipr("BatteryLifeValue")
}
})
b.Run("ToSnakeCase", func(b *testing.B) {
for i := 0; i < b.N; i++ {
ToSnakeCase("BatteryLifeValue")
}
})
}
func BenchmarkAllInOne(b *testing.B) {
b.Run("ToSnakeCaseRegex", func(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, item := range cases {
arg := item.args
ToSnakeCaseRegex(arg)
}
}
})
b.Run("ToSnakeCaseByJensSkipr", func(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, item := range cases {
arg := item.args
ToSnakeCaseByJensSkipr(arg)
}
}
})
b.Run("ToSnakeCase", func(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, item := range cases {
arg := item.args
ToSnakeCase(arg)
}
}
})
}
var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)")
var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
func ToSnakeCaseRegex(str string) string {
snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}")
snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}")
return strings.ToLower(snake)
}
func ToSnakeCaseByJensSkipr(s string) string {
var res = make([]rune, 0, len(s))
var p = '_'
for i, r := range s {
if !unicode.IsLetter(r) && !unicode.IsDigit(r) {
res = append(res, '_')
} else if unicode.IsUpper(r) && i > 0 {
if unicode.IsLetter(p) && !unicode.IsUpper(p) || unicode.IsDigit(p) {
res = append(res, '_', unicode.ToLower(r))
} else {
res = append(res, unicode.ToLower(r))
}
} else {
res = append(res, unicode.ToLower(r))
}
p = r
}
return string(res)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment