-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathchunk.go
More file actions
96 lines (79 loc) · 1.79 KB
/
chunk.go
File metadata and controls
96 lines (79 loc) · 1.79 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
package caseconv
import (
"strings"
"unicode"
)
func chunk(str string) []string {
var (
cp chunkerPredicate
parts []string
)
parts = chunkBy(str, cp.run)
buffer := parts
parts = make([]string, len(buffer))
for i, part := range buffer {
parts[i] = strings.ToLower(part)
}
return parts
}
type chunkerPredicate struct{ lastRune rune }
func (cp *chunkerPredicate) run(r, next rune) (split, drop bool) {
defer func() { cp.lastRune = r }()
var (
br = breakRune(r)
bnext = breakRune(next)
blast = breakRune(cp.lastRune)
)
switch {
case br.isSplitter():
split, drop = true, true
case cp.lastRune == 0:
return
case next != 0 && br.isUppercase() &&
blast.isUppercase() &&
bnext.isLowercase(),
(blast.isLowercase() || blast.isNumber()) &&
br.isUppercase():
split = true
}
return
}
type breakRune rune
func (br breakRune) isLowercase() bool { return unicode.IsLower(rune(br)) }
func (br breakRune) isNumber() bool { return unicode.IsDigit(rune(br)) }
func (br breakRune) isUppercase() bool { return unicode.IsUpper(rune(br)) }
func (br breakRune) isSplitter() bool {
return br == '_' || br == ' ' || br == '.' || br == '/' || br == '"'
}
func chunkBy(str string, chunkFn func(r, next rune) (split, drop bool)) []string {
var (
lastChunk []rune
result []string
)
runes := []rune(str)
for i, r := range runes {
var next rune
if i < len(runes)-1 {
next = runes[i+1]
}
split, drop := chunkFn(r, next)
if !split && !drop {
lastChunk = append(lastChunk, r)
continue
}
if split {
if len(lastChunk) > 0 {
result = append(result, string(lastChunk))
}
lastChunk = nil
if !drop {
lastChunk = append(lastChunk, r)
}
continue
}
}
if len(lastChunk) > 0 {
result = append(result, string(lastChunk))
}
return result
}