-
Notifications
You must be signed in to change notification settings - Fork 530
/
helpers.go
84 lines (75 loc) · 1.79 KB
/
helpers.go
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package goose
import (
"bytes"
"strings"
"unicode"
"unicode/utf8"
)
type camelSnakeStateMachine int
const ( // _$$_This is some text, OK?!
idle camelSnakeStateMachine = iota // 0 ↑ ↑ ↑
firstAlphaNum // 1 ↑ ↑ ↑ ↑ ↑
alphaNum // 2 ↑↑↑ ↑ ↑↑↑ ↑↑↑ ↑
delimiter // 3 ↑ ↑ ↑ ↑ ↑
)
func (s camelSnakeStateMachine) next(r rune) camelSnakeStateMachine {
switch s {
case idle:
if isAlphaNum(r) {
return firstAlphaNum
}
case firstAlphaNum:
if isAlphaNum(r) {
return alphaNum
}
return delimiter
case alphaNum:
if !isAlphaNum(r) {
return delimiter
}
case delimiter:
if isAlphaNum(r) {
return firstAlphaNum
}
return idle
}
return s
}
func camelCase(str string) string {
var b strings.Builder
stateMachine := idle
for i := 0; i < len(str); {
r, size := utf8.DecodeRuneInString(str[i:])
i += size
stateMachine = stateMachine.next(r)
switch stateMachine {
case firstAlphaNum:
b.WriteRune(unicode.ToUpper(r))
case alphaNum:
b.WriteRune(unicode.ToLower(r))
}
}
return b.String()
}
func snakeCase(str string) string {
var b bytes.Buffer
stateMachine := idle
for i := 0; i < len(str); {
r, size := utf8.DecodeRuneInString(str[i:])
i += size
stateMachine = stateMachine.next(r)
switch stateMachine {
case firstAlphaNum, alphaNum:
b.WriteRune(unicode.ToLower(r))
case delimiter:
b.WriteByte('_')
}
}
if stateMachine == idle {
return string(bytes.TrimSuffix(b.Bytes(), []byte{'_'}))
}
return b.String()
}
func isAlphaNum(r rune) bool {
return unicode.IsLetter(r) || unicode.IsNumber(r)
}