File: snake.go

package info (click to toggle)
golang-github-scaleway-scaleway-sdk-go 1.0.0~beta12-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 3,000 kB
  • sloc: javascript: 160; sh: 70; makefile: 3
file content (37 lines) | stat: -rw-r--r-- 846 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
37
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
			}
		}

		if i > 0 && n[len(n)-1] != '_' && nextCaseIsChanged {
			// add underscore if next letter case type is changed
			if isUpperLetter(v) {
				n += "_" + string(v)
			} else if isLowerLetter(v) {
				n += string(v) + "_"
			}
		} else if v == ' ' || v == '-' {
			// replace spaces and dashes with underscores
			n += "_"
		} else {
			n = n + string(v)
		}
	}
	n = strings.ToLower(n)
	return n
}