-
Notifications
You must be signed in to change notification settings - Fork 1
/
take.go
81 lines (71 loc) · 1.44 KB
/
take.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
package glinq
import (
"io"
)
type (
TakeIterator[T any] struct {
iterator[T]
source IEnumerable[T]
take, pos int
enumerator IEnumerator[T]
}
)
func NewTakeIterator[T any](source IEnumerable[T], n int) *TakeIterator[T] {
result := &TakeIterator[T]{
source: source,
take: n,
}
result.child = result
return result
}
func Take[T any](source IEnumerable[T], n int) IEnumerable[T] {
return NewTakeIterator(source, n)
}
func (me *TakeIterator[T]) Clone() IEnumerator[T] {
result := NewTakeIterator(me.source, me.take)
result.state = 1
return result
}
func (me *TakeIterator[T]) MoveNext() error {
if me.pos >= me.take {
return io.EOF
}
me.pos++
switch me.state {
case 1:
enumerator := me.source.GetEnumerator()
me.enumerator = enumerator
me.state = 2
fallthrough
case 2:
err := me.enumerator.MoveNext()
me.current = me.enumerator.Current()
return err
}
return ErrInvalidState
}
func (me *TakeIterator[T]) Any() bool {
if me.take == 0 {
return false
}
return me.source.Any()
}
func (me *TakeIterator[T]) Count() int {
iter := me.source.GetEnumerator()
if counter, ok := iter.(ICount[T]); ok {
result := counter.Count()
if result > me.take {
result = me.take
}
return result
}
result := 0
Foreach(me.source, func(T) error {
result++
if result < me.take {
return nil
}
return io.EOF
})
return result
}