| 1 |
package blhistory |
| 2 |
|
| 3 |
import ( |
| 4 |
"time" |
| 5 |
) |
| 6 |
|
| 7 |
// BLHistory is a browser-like history: we can add more items to the history; |
| 8 |
// we can go back and forth; when we're a few items back and we add a new item, |
| 9 |
// a new item is added at this place in the history and all the previously existing |
| 10 |
// newer items are dropped; there is no persistence. |
| 11 |
// |
| 12 |
// A cache can be added to every history item too, but that's a TODO. |
| 13 |
type BLHistory struct { |
| 14 |
items []Item |
| 15 |
|
| 16 |
curIdx int |
| 17 |
} |
| 18 |
|
| 19 |
type Item struct { |
| 20 |
Time time.Time |
| 21 |
|
| 22 |
Str string |
| 23 |
} |
| 24 |
|
| 25 |
func New() *BLHistory { |
| 26 |
h := &BLHistory{} |
| 27 |
|
| 28 |
return h |
| 29 |
} |
| 30 |
|
| 31 |
func (h *BLHistory) Add(s string) { |
| 32 |
item := Item{ |
| 33 |
Time: time.Now(), |
| 34 |
Str: s, |
| 35 |
} |
| 36 |
|
| 37 |
if len(h.items) > 0 && h.curIdx < len(h.items)-1 { |
| 38 |
h.items = h.items[:h.curIdx+1] |
| 39 |
} |
| 40 |
|
| 41 |
h.items = append(h.items, item) |
| 42 |
h.curIdx = len(h.items) - 1 |
| 43 |
} |
| 44 |
|
| 45 |
func (h *BLHistory) Prev() *Item { |
| 46 |
if h.curIdx == 0 { |
| 47 |
return nil |
| 48 |
} |
| 49 |
|
| 50 |
h.curIdx-- |
| 51 |
|
| 52 |
item := h.items[h.curIdx] |
| 53 |
return &item |
| 54 |
} |
| 55 |
|
| 56 |
func (h *BLHistory) Next() *Item { |
| 57 |
if h.curIdx >= len(h.items)-1 { |
| 58 |
return nil |
| 59 |
} |
| 60 |
|
| 61 |
h.curIdx++ |
| 62 |
|
| 63 |
item := h.items[h.curIdx] |
| 64 |
return &item |
| 65 |
} |