generated from tbistr/golang-vscode-devcontainer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinc.go
87 lines (76 loc) · 1.92 KB
/
inc.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
85
86
87
package inc
// Match does naive incremental search.
func Match(query string, body string) bool {
if len(query) == 0 {
return true
}
queryRunes := []rune(query)
cursor := 0
for _, c := range body {
if c == queryRunes[cursor] {
cursor++
}
if cursor == len(query) {
return true
}
}
return false
}
// Engine is a engine for incremental search.
type Engine struct {
cands []*Candidate
Algorithm
}
// New returns a new Engine.
//
// It uses the default algorithm which is naive incremental search.
func New(query string, cands []Candidate) *Engine {
return NewWithAlgo(query, cands, &defaultAlgo{})
}
// NewWithAlgo returns a new Engine with a custom algorithm.
func NewWithAlgo(query string, cands []Candidate, algo Algorithm) *Engine {
e := &Engine{Algorithm: algo}
e.AppendCands(cands)
for _, r := range query {
e.AddQuery(r)
}
return e
}
// AppendCands appends candidates to the engine.
//
// It receives candidates as values and converts them to pointers.
// So, you can't modify the candidates after passing them to AppendCands.
func (e *Engine) AppendCands(cands []Candidate) {
pCands := make([]*Candidate, len(cands))
for i, c := range cands {
p := c // Loop var c is overwritten in each iteration.
pCands[i] = &p
}
e.Algorithm.AppendCands(pCands)
e.cands = append(e.cands, pCands...)
}
// DeleteCands deletes all candidates from the engine.
func (e *Engine) DeleteCands() {
e.Algorithm.DeleteCands()
e.cands = nil
}
// Candidates returns all candidates.
func (e *Engine) Candidates() []Candidate {
cs := make([]Candidate, 0, len(e.cands))
for _, c := range e.cands {
cs = append(cs, *c)
}
return cs
}
// Matched returns matched candidates.
//
// It returns candidates as values, so you can't modify internal states of the engine.
func (e *Engine) Matched() []Candidate {
matched := []Candidate{}
for _, c := range e.cands {
if c.Matched {
matched = append(matched, *c)
}
}
return matched
}