mirror of
https://github.com/duke-git/lancet.git
synced 2026-11-16 05:12:11 +08:00
fix(package): [iterator] report available elements in HasNext (#392)
This commit is contained in:
1 parent
9685357daf
commit
be3bc0c43f
2 files changed
+39
-2
No files matched your search
@@ -0,0 +1,26 @@
|
||||
package iterator
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestTakeHasNextExhaustedSource(t *testing.T) {
|
||||
it := Take[int](FromSlice([]int{1}), 3)
|
||||
if value, ok := it.Next(); !ok || value != 1 {
|
||||
t.Fatal("missing first value")
|
||||
}
|
||||
if it.HasNext() {
|
||||
t.Error("exhausted source still reports an element")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterHasNextMatches(t *testing.T) {
|
||||
it := Filter[int](FromSlice([]int{1, 2, 3}), func(value int) bool { return value%2 == 0 })
|
||||
if !it.HasNext() || !it.HasNext() {
|
||||
t.Fatal("missing matching value")
|
||||
}
|
||||
if value, ok := it.Next(); !ok || value != 2 {
|
||||
t.Fatal("HasNext consumed the matching value")
|
||||
}
|
||||
if it.HasNext() {
|
||||
t.Error("unmatched tail reported as another element")
|
||||
}
|
||||
}
|
||||
+13
-2
@@ -44,9 +44,17 @@ func Filter[T any](iter Iterator[T], predicateFunc func(item T) bool) Iterator[T
|
||||
type filterIterator[T any] struct {
|
||||
iter Iterator[T]
|
||||
predicateFunc func(T) bool
|
||||
next T
|
||||
ready bool
|
||||
}
|
||||
|
||||
func (fr *filterIterator[T]) Next() (T, bool) {
|
||||
if fr.ready {
|
||||
item := fr.next
|
||||
var zero T
|
||||
fr.next, fr.ready = zero, false
|
||||
return item, true
|
||||
}
|
||||
for item, ok := fr.iter.Next(); ok; item, ok = fr.iter.Next() {
|
||||
if fr.predicateFunc(item) {
|
||||
return item, true
|
||||
@@ -57,7 +65,10 @@ func (fr *filterIterator[T]) Next() (T, bool) {
|
||||
}
|
||||
|
||||
func (fr *filterIterator[T]) HasNext() bool {
|
||||
return fr.iter.HasNext()
|
||||
if !fr.ready {
|
||||
fr.next, fr.ready = fr.Next()
|
||||
}
|
||||
return fr.ready
|
||||
}
|
||||
|
||||
// Join creates an iterator that join all elements of iters[0], then all elements of iters[1] and so on.
|
||||
@@ -135,5 +146,5 @@ func (iter *takeIterator[T]) Next() (T, bool) {
|
||||
}
|
||||
|
||||
func (iter *takeIterator[T]) HasNext() bool {
|
||||
return iter.num > 0
|
||||
return iter.num > 0 && iter.it.HasNext()
|
||||
}
|
||||
Reference in new issue
Block a user