-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbasichistorymanager.go
94 lines (74 loc) · 1.51 KB
/
basichistorymanager.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
88
89
90
91
92
93
94
package ns
import (
"sort"
"github.com/hashibuto/nimble"
)
type BasicHistoryManager struct {
index *nimble.IndexedDequeue
maxKeep int
prev string
}
type BasicHistoryIterator struct {
iter *nimble.IndexedDequeIterator
}
func (bhi *BasicHistoryIterator) Forward() string {
if bhi.iter == nil {
return ""
}
bhi.iter.Next()
return bhi.iter.Value()
}
func (bhi *BasicHistoryIterator) Backward() string {
if bhi.iter == nil {
return ""
}
bhi.iter.ReverseNext()
return bhi.iter.Value()
}
func NewBasicHistoryManager(maxKeep int) *BasicHistoryManager {
return &BasicHistoryManager{
index: nimble.NewIndexedDequeue(),
maxKeep: maxKeep,
}
}
func (h *BasicHistoryManager) Push(value string) {
if value == h.prev {
return
}
h.prev = value
h.index.Push(value)
if h.index.Size() > h.maxKeep {
h.index.Pop()
}
}
func (h *BasicHistoryManager) GetIterator() HistoryIterator {
if h.index.Size() > 0 {
return &BasicHistoryIterator{
iter: h.index.GetIter(),
}
}
return &BasicHistoryIterator{}
}
func (h *BasicHistoryManager) Search(pattern string) []string {
if h.index.Size() == 0 {
return nil
}
if len(pattern) == 0 {
return nil
}
links := h.index.Find(pattern)
if len(links) == 0 {
return nil
}
// sort from most recent to oldest
sort.Slice(links, func(i, j int) bool {
return links[i].CreatedAt.After(links[j].CreatedAt)
})
strs := make([]string, len(links))
for i, link := range links {
strs[i] = link.Value
}
return strs
}
func (h *BasicHistoryManager) Exit() {
}