Live video on the AT Protocol
1package config
2
3import "strings"
4
5func ToSnakeCase(str string) string {
6 out := ""
7 runes := []rune(str)
8
9 for i, c := range runes {
10 ch := string(c)
11 isUpper := strings.ToUpper(ch) == ch && strings.ToLower(ch) != ch
12
13 if isUpper {
14 // Add dash before uppercase letter if:
15 // 1. It's not the first character AND
16 // 2. Either the previous character is lowercase OR the next character is lowercase
17 if i > 0 {
18 prevIsLower := i > 0 && strings.ToLower(string(runes[i-1])) == string(runes[i-1])
19 nextIsLower := i < len(runes)-1 && strings.ToLower(string(runes[i+1])) == string(runes[i+1])
20
21 if prevIsLower || nextIsLower {
22 out += "-"
23 }
24 }
25 out += strings.ToLower(ch)
26 } else {
27 out += ch
28 }
29 }
30 return out
31}