| 1 |
|
| 2 |
package selector |
| 3 |
|
| 4 |
|
| 5 |
type Selector[T any] struct { |
| 6 |
items []T |
| 7 |
index int |
| 8 |
} |
| 9 |
|
| 10 |
|
| 11 |
func NewSelector[T any](items []T) *Selector[T] { |
| 12 |
return &Selector[T]{ |
| 13 |
items: items, |
| 14 |
} |
| 15 |
} |
| 16 |
|
| 17 |
|
| 18 |
func (s *Selector[T]) Append(item T) { |
| 19 |
s.items = append(s.items, item) |
| 20 |
} |
| 21 |
|
| 22 |
|
| 23 |
func (s *Selector[T]) Next() { |
| 24 |
if s.index < len(s.items)-1 { |
| 25 |
s.index++ |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
|
| 30 |
func (s *Selector[T]) Prev() { |
| 31 |
if s.index > 0 { |
| 32 |
s.index-- |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
|
| 37 |
func (s *Selector[T]) OnFirst() bool { |
| 38 |
return s.index == 0 |
| 39 |
} |
| 40 |
|
| 41 |
|
| 42 |
func (s *Selector[T]) OnLast() bool { |
| 43 |
return s.index == len(s.items)-1 |
| 44 |
} |
| 45 |
|
| 46 |
|
| 47 |
func (s *Selector[T]) Selected() T { |
| 48 |
return s.items[s.index] |
| 49 |
} |
| 50 |
|
| 51 |
|
| 52 |
func (s *Selector[T]) Index() int { |
| 53 |
return s.index |
| 54 |
} |
| 55 |
|
| 56 |
|
| 57 |
func (s *Selector[T]) Total() int { |
| 58 |
return len(s.items) |
| 59 |
} |
| 60 |
|
| 61 |
|
| 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 |
|
| 70 |
func (s *Selector[T]) Get(i int) T { |
| 71 |
return s.items[i] |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
func (s *Selector[T]) Set(i int, item T) { |
| 76 |
s.items[i] = item |
| 77 |
} |
| 78 |
|
| 79 |
|
| 80 |
|
| 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 |
|
| 90 |
|
| 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 |
} |