-
-
Save stoewer/fbe273b711e6a06315d19552dd4d33e6 to your computer and use it in GitHub Desktop.
| import ( | |
| "fmt" | |
| "strings" | |
| "regexp" | |
| ) | |
| var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)") | |
| var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])") | |
| func ToSnakeCase(str string) string { | |
| snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}") | |
| snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}") | |
| return strings.ToLower(snake) | |
| } |
Hi, I make one more, but it pass all test, and better performance.
source file in here: https://gist.github.com/hxsf/7f5392c0153d3a8607c42eefed02b8cd
Bench
> go test -benchmem -bench 'One'
goos: darwin
goarch: amd64
pkg: mesh-sidecar/cmd/vars
cpu: Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz
BenchmarkOneCase/ToSnakeCaseRegex-8 490156 2403 ns/op 305 B/op 12 allocs/op
BenchmarkOneCase/ToSnakeCaseByJensSkipr-8 4163742 286.1 ns/op 216 B/op 3 allocs/op
BenchmarkOneCase/ToSnakeCase-8 8867581 131.4 ns/op 24 B/op 1 allocs/op
BenchmarkAllInOne/ToSnakeCaseRegex-8 51538 22480 ns/op 2307 B/op 137 allocs/op
BenchmarkAllInOne/ToSnakeCaseByJensSkipr-8 395026 3051 ns/op 1352 B/op 41 allocs/op
BenchmarkAllInOne/ToSnakeCase-8 857940 1491 ns/op 232 B/op 17 allocs/op
PASS
ok mesh-sidecar/cmd/vars 7.930s@hxsf looks awesome! Yeah, I forgot about additional capacity for underscores %)
@hxsf: That looks great! Do you mind adding a license to your gist?
@adombeck add MIT license.
@hxsf: Great, thanks a lot!
@hxsf Test failed for
MyLIFEIsAwesomE should be my_life_is_awesom_e but got mylife_is_awesome
Japan125Canada130Australia150 should be japan125_canada130_australia150 but got japan1_2_5_canada1_3_0_australia1_5_0
@elvizlai I update the code. and it works
good guys ! keep it up!
kebab case should be concluded here as well
@abdennour just replace '_' with '-' in the code, and change the function name. I think it will work.
@porfirion thanks for the proposal and comparison! I noticed most of my unit test fail when using your version. Therefore, I tried to make a version which succeeds (nearly) all tests. It can still use some cleanup and unit test for
HTTPRequeststill fails, but nearly same performance improvements.Code
Benchmarks
Results