Skip to content

Commit

Permalink
Add SkipWhile and TakeWhile
Browse files Browse the repository at this point in the history
  • Loading branch information
Ismail Gjevori committed Mar 21, 2022
1 parent cdb1698 commit a7a8049
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions iterator.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,18 @@ func (it Iterator[T]) Skip(count int) Iterator[T] {
}
}

// SkipWhile will skip the first elements that satisfy the test.
func (it Iterator[T]) SkipWhile(test func(item T) bool) Iterator[T] {
skipped := false
return func() (T, bool) {
if !skipped {
skipped = true
return it.Find(func(item T) bool { return !test(item) })
}
return it()
}
}

// Take will yield at most the first `count` values.
func (it Iterator[T]) Take(count int) Iterator[T] {
taken := 0
Expand All @@ -125,6 +137,21 @@ func (it Iterator[T]) Take(count int) Iterator[T] {
}
}

// TakeWhile will stop at the first value that does not satisfy the test.
func (it Iterator[T]) TakeWhile(test func(item T) bool) Iterator[T] {
stopped := false
return func() (T, bool) {
if stopped {
return *new(T), false
}
if i, ok := it(); ok && test(i) {
return i, ok
}
stopped = true
return *new(T), false
}
}

// Reverse will consume the iterator, collect the values in a `Vec` and iterate in reverse those values.
// Since `Reverse` will consume the iterator and allocate a `Vec`, when possible use `Vec.ReverseIter`.
func (it Iterator[T]) Reverse() Iterator[T] {
Expand Down

0 comments on commit a7a8049

Please # to comment.