Skip to content

Instantly share code, notes, and snippets.

@jose-neta
Forked from elwinar/snake.go
Created December 1, 2018 19:33
Show Gist options
  • Save jose-neta/7957cb93ca9da34d6b475fa7ef73b8e3 to your computer and use it in GitHub Desktop.
Save jose-neta/7957cb93ca9da34d6b475fa7ef73b8e3 to your computer and use it in GitHub Desktop.
ToSnake function for golang, convention-compliant
package main
import (
"unicode"
)
// ToSnake convert the given string to snake case following the Golang format:
// acronyms are converted to lower-case and preceded by an underscore.
func ToSnake(in string) string {
runes := []rune(in)
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])) {
out = append(out, '_')
}
out = append(out, unicode.ToLower(runes[i]))
}
return string(out)
}
package main
import (
"strings"
"testing"
)
type SnakeTest struct {
input string
output string
}
var tests = []SnakeTest{
{"a", "a"},
{"snake", "snake"},
{"A", "a"},
{"ID", "id"},
{"MOTD", "motd"},
{"Snake", "snake"},
{"SnakeTest", "snake_test"},
{"SnakeID", "snake_id"},
{"SnakeIDGoogle", "snake_id_google"},
{"LinuxMOTD", "linux_motd"},
{"OMGWTFBBQ", "omgwtfbbq"},
{"omg_wtf_bbq", "omg_wtf_bbq"},
}
func TestToSnake(t *testing.T) {
for _, test := range tests {
if ToSnake(test.input) != test.output {
t.Errorf(`ToSnake("%s"), wanted "%s", got \%s"`, test.input, test.output, ToSnake(test.input))
}
}
}
var benchmarks = []string{
"a",
"snake",
"A",
"Snake",
"SnakeTest",
"SnakeID",
"SnakeIDGoogle",
"LinuxMOTD",
"OMGWTFBBQ",
"omg_wtf_bbq",
}
func BenchmarkToSnake(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, input := range benchmarks {
ToSnake(input)
}
}
}
func BenchmarkToLower(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, input := range benchmarks {
strings.ToLower(input)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment