1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-12 00:32:27 +08:00

feat: add take iterator

This commit is contained in:
dudaodong
2022-12-26 17:20:14 +08:00
parent b06fb6736d
commit 65315dafb1
2 changed files with 36 additions and 0 deletions

View File

@@ -112,3 +112,28 @@ func Reduce[T any, U any](iter Iterator[T], initial U, reducer func(U, T) U) U {
return acc
}
func Take[T any](it Iterator[T], num int) Iterator[T] {
return &takeIterator[T]{it: it, num: num}
}
type takeIterator[T any] struct {
it Iterator[T]
num int
}
func (iter *takeIterator[T]) Next() (T, bool) {
if iter.num <= 0 {
var zero T
return zero, false
}
item, ok := iter.it.Next()
if ok {
iter.num--
}
return item, ok
}
func (iter *takeIterator[T]) HasNext() bool {
return iter.num > 0
}