-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
78 lines (66 loc) · 1.58 KB
/
parser.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
package textcase
import (
"strings"
"unicode"
"unicode/utf8"
)
type parser int
const (
_ parser = iota // _$$_This is some text, OK?!
idle // 1 ↑↑↑↑ ↑ ↑
firstAlphaNum // 2 ↑ ↑ ↑ ↑ ↑
alphaNum // 3 ↑↑↑ ↑ ↑↑↑ ↑↑↑ ↑
delimiter // 4 ↑ ↑ ↑ ↑ ↑
)
func (s parser) next(r rune) parser {
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 isAlphaNum(r rune) bool {
return unicode.IsLetter(r) || unicode.IsNumber(r)
}
// Mark letter case changes, ie. "camelCaseTEXT" -> "camel_Case_TEXT".
func markLetterCaseChanges(input string) string {
var b strings.Builder
wasLetter := false
countConsecutiveUpperLetters := 0
for i := 0; i < len(input); {
r, size := utf8.DecodeRuneInString(input[i:])
i += size
if unicode.IsLetter(r) {
if wasLetter && countConsecutiveUpperLetters > 1 && !unicode.IsUpper(r) {
b.WriteString("_")
}
if wasLetter && countConsecutiveUpperLetters == 0 && unicode.IsUpper(r) {
b.WriteString("_")
}
}
wasLetter = unicode.IsLetter(r)
if unicode.IsUpper(r) {
countConsecutiveUpperLetters++
} else {
countConsecutiveUpperLetters = 0
}
b.WriteRune(r)
}
return b.String()
}