Debian Codegraph @

internal/selector/selector.go

raw symbols SCIP
1 // Package selector provides a helper type for selecting items.
2 package selector
3
4 // Selector is a helper type for selecting items.
5 type Selector[T any] struct {
6 items []T
7 index int
8 }
9
10 // NewSelector creates a new item selector.
11 func NewSelector[T any](items []T) *Selector[T] {
12 return &Selector[T]{
13 items: items,
14 }
15 }
16
17 // Append adds an item to the selector.
18 func (s *Selector[T]) Append(item T) {
19 s.items = append(s.items, item)
20 }
21
22 // Next moves the selector to the next item.
23 func (s *Selector[T]) Next() {
24 if s.index < len(s.items)-1 {
25 s.index++
26 }
27 }
28
29 // Prev moves the selector to the previous item.
30 func (s *Selector[T]) Prev() {
31 if s.index > 0 {
32 s.index--
33 }
34 }
35
36 // OnFirst returns true if the selector is on the first item.
37 func (s *Selector[T]) OnFirst() bool {
38 return s.index == 0
39 }
40
41 // OnLast returns true if the selector is on the last item.
42 func (s *Selector[T]) OnLast() bool {
43 return s.index == len(s.items)-1
44 }
45
46 // Selected returns the index of the current selected item.
47 func (s *Selector[T]) Selected() T {
48 return s.items[s.index]
49 }
50
51 // Index returns the index of the current selected item.
52 func (s *Selector[T]) Index() int {
53 return s.index
54 }
55
56 // Total returns the total number of items.
57 func (s *Selector[T]) Total() int {
58 return len(s.items)
59 }
60
61 // SetIndex sets the selected item.
62 func (s *Selector[T]) SetIndex(i int) {
63 if i < 0 || i >= len(s.items) {
64 return
65 }
66 s.index = i
67 }
68
69 // Get returns the item at the given index.
70 func (s *Selector[T]) Get(i int) T {
71 return s.items[i]
72 }
73
74 // Set sets the item at the given index.
75 func (s *Selector[T]) Set(i int, item T) {
76 s.items[i] = item
77 }
78
79 // Range iterates over the items.
80 // The callback function should return true to continue the iteration.
81 func (s *Selector[T]) Range(f func(i int, item T) bool) {
82 for i, item := range s.items {
83 if !f(i, item) {
84 break
85 }
86 }
87 }
88
89 // ReverseRange iterates over the items in reverse.
90 // The callback function should return true to continue the iteration.
91 func (s *Selector[T]) ReverseRange(f func(i int, item T) bool) {
92 for i := len(s.items) - 1; i >= 0; i-- {
93 if !f(i, s.items[i]) {
94 break
95 }
96 }
97 }