-
Notifications
You must be signed in to change notification settings - Fork 0
/
history.go
105 lines (80 loc) · 1.65 KB
/
history.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
95
96
97
98
99
100
101
102
103
104
105
package go_input_history
import (
"sync"
)
// History struct to hold the history of the user input
type History struct {
Max int
Data []string
Index int
mu sync.Mutex
}
// New history struct
func New(max int) *History {
return &History{
Max: max,
Data: []string{},
Index: 0,
}
}
// Add line to history
func (h *History) Add(line string) {
h.mu.Lock()
defer h.mu.Unlock()
previous := h.Prev()
if line == previous {
return
}
// remove the left most element if we have reached the max to make way for the new element
if len(h.Data) > h.Max {
h.Data = append(h.Data[:0], h.Data[1:]...)
}
h.Data = append(h.Data, line)
h.Index = len(h.Data) - 1
}
// HasLine will return true if the history buffer contains the given string
func (h *History) HasLine(line string) bool {
for _, l := range h.Data {
if line == l {
return true
}
}
return false
}
// Get history at index
func (h *History) Get(index int) string {
return h.Data[index]
}
// IsEmpty return true if the history data array is empty
func (h *History) IsEmpty() bool {
if len(h.Data) <= 0 {
return true
}
return false
}
// Prev returns the previous history line from the current index
func (h *History) Prev() string {
h.Index--
if h.Index < 0 {
h.Index = 0
}
if h.IsEmpty() {
return ""
}
return h.Data[h.Index]
}
// Next returns the history line after the current index
func (h *History) Next() string {
h.Index++
if h.Index >= len(h.Data) {
h.Index = len(h.Data) - 1
}
if h.IsEmpty() {
return ""
}
return h.Data[h.Index]
}
// SetIndexToNew sets the index to the new elements index
func (h *History) SetIndexToNew() {
h.Index = len(h.Data)
}