feat: stuff
This commit is contained in:
@@ -12,8 +12,8 @@ type Iterator[T any] struct {
|
||||
}
|
||||
|
||||
// Create a new iterator, over a set of items.
|
||||
func New[T any](items []T) Iterator[T] {
|
||||
return Iterator[T]{data: items, index: 0}
|
||||
func New[T any](items []T) *Iterator[T] {
|
||||
return &Iterator[T]{data: items, index: 0}
|
||||
}
|
||||
|
||||
// Returns the current position of the iterator.
|
||||
@@ -40,7 +40,7 @@ func (i Iterator[T]) Peek() (T, error) {
|
||||
|
||||
// Moves the iterator pointer to the next item. Returns the current item. Fails
|
||||
// if there are no more items to iterate over.
|
||||
func (i *Iterator[T]) Next() (T, error) {
|
||||
func (i *Iterator[T]) Pop() (T, error) {
|
||||
val, err := i.Peek()
|
||||
if err != nil {
|
||||
return val, err
|
||||
@@ -49,3 +49,22 @@ func (i *Iterator[T]) Next() (T, error) {
|
||||
i.index++
|
||||
return val, nil
|
||||
}
|
||||
|
||||
// Pop until the clause returns false.
|
||||
func (i *Iterator[T]) PopWhile(fn func(T) bool) []T {
|
||||
result := []T{}
|
||||
|
||||
for {
|
||||
popped, err := i.Peek()
|
||||
if err != nil || !fn(popped) {
|
||||
break
|
||||
}
|
||||
|
||||
result = append(result, popped)
|
||||
if _, err := i.Pop(); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user