/
ienumerator.go
60 lines (47 loc) · 1.17 KB
/
ienumerator.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
package goe
import "fmt"
var _ IEnumerator[any] = &enumerator[any]{}
type enumerator[T any] struct {
data []T
position int
}
// NewIEnumerator returns a new IEnumerator instance from source slice
func NewIEnumerator[T any](source ...T) IEnumerator[T] {
return &enumerator[T]{
data: copySlice(source),
position: -1,
}
}
// Current is implementation for IEnumerator
func (col *enumerator[T]) Current() T {
col.assertCollectionNonNil()
result, err := col.CurrentSafe()
if err != nil {
panic(err)
}
return result
}
// MoveNext is implementation for IEnumerator
func (col *enumerator[T]) MoveNext() bool {
col.assertCollectionNonNil()
if col.position >= len(col.data)-1 {
return false
}
col.position++
return true
}
// Reset is implementation for IEnumerator
func (col *enumerator[T]) Reset() {
col.assertCollectionNonNil()
col.position = -1
}
// CurrentSafe is implementation for an extra method of IEnumerator
func (col *enumerator[T]) CurrentSafe() (result T, err error) {
col.assertCollectionNonNil()
if col.position < 0 || col.position > len(col.data)-1 {
err = fmt.Errorf("invalid operation")
return
}
result = col.data[col.position]
return
}