Completed
Push — master ( b483f1...082c99 )
by Valentin
02:29
created

util.SplitKeywords   B

Complexity

Conditions 7

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 13
nop 1
dl 0
loc 24
rs 8
c 0
b 0
f 0
1
package util
2
3
import (
4
	"strings"
5
	"unicode"
6
)
7
8
var (
9
	separators = &unicode.RangeTable{
10
		R16: []unicode.Range16{
11
			{0x002c, 0x002c, 1}, //comma
12
			{0x003b, 0x003b, 1}, //semicolon
13
		},
14
	}
15
	quotationMarks = &unicode.RangeTable{
16
		R16: []unicode.Range16{
17
			{0x0022, 0x0022, 1}, //quot
18
		},
19
	}
20
	trimRunes = `,; "`
21
)
22
23
type tokenizer struct {
24
	keyword   string
25
	keywords  []string
26
	lastIndex int
27
	quotFound bool
28
}
29
30
var t tokenizer
31
32
func (t *tokenizer) addKeyword(input string, index int) {
33
	keyword := fetchKeyword(input, t.lastIndex, index)
34
	t.lastIndex = index
35
36
	if len(keyword) != 0 {
37
		t.append(keyword)
38
	}
39
}
40
41
func (t *tokenizer) append(keyword string) {
42
	t.keywords = append(t.keywords, keyword)
43
}
44
45
func (t *tokenizer) toggleQuot() {
46
	t.quotFound = !t.quotFound
47
}
48
49
func SplitKeywords(input string) []string {
50
	t = tokenizer{}
51
52
	for index, r := range []rune(input) {
53
		if unicode.In(r, separators) && !t.quotFound {
54
			t.addKeyword(input, index)
55
56
			continue
57
		}
58
59
		if index == len(input)-1 {
60
			t.addKeyword(input, len(input))
61
62
			continue
63
		}
64
65
		if unicode.In(r, quotationMarks) {
66
			t.toggleQuot()
67
68
			continue
69
		}
70
	}
71
72
	return t.keywords
73
}
74
75
func fetchKeyword(input string, start, end int) string {
76
	return trim(cut(input, start, end))
77
}
78
79
func trim(input string) string {
80
	return strings.Trim(input, trimRunes)
81
}
82
83
func cut(input string, start, end int) string {
84
	r := []rune(input)
85
	if end > len(r) {
86
		end = len(r)
87
	}
88
89
	return string(r[start:end])
90
}
91