File: snake.go

package info (click to toggle)
golang-github-scaleway-scaleway-sdk-go 1.0.0~beta32-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,444 kB
  • sloc: sh: 70; makefile: 3
file content (36 lines) | stat: -rw-r--r-- 743 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package strcase

import (
	"strings"
)

// Converts a string to snake_case
func ToSnake(s string) string {
	s = strings.Trim(s, " ")
	n := ""
	for i, v := range s {
		// treat acronyms as words, eg for JSONData -> JSON is a whole word
		nextCaseIsChanged := false
		if i+1 < len(s) {
			next := s[i+1]
			if (isUpperLetter(v) && isLowerLetter(int32(next))) || (isLowerLetter(v) && isUpperLetter(int32(next))) {
				nextCaseIsChanged = true
			}
		}

		switch {
		case i > 0 && n[len(n)-1] != '_' && nextCaseIsChanged:
			if isUpperLetter(v) {
				n += "_" + string(v)
			} else if isLowerLetter(v) {
				n += string(v) + "_"
			}
		case v == ' ' || v == '-':
			n += "_"
		default:
			n += string(v)
		}
	}
	n = strings.ToLower(n)
	return n
}