feat: better recursive descent
This commit is contained in:
@@ -7,13 +7,13 @@ import "fmt"
|
||||
|
||||
// An iterator over slices.
|
||||
type Iterator[T any] struct {
|
||||
data []T
|
||||
items []T
|
||||
index int
|
||||
}
|
||||
|
||||
// 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 Of[T any](items []T) *Iterator[T] {
|
||||
return &Iterator[T]{items: items, index: 0}
|
||||
}
|
||||
|
||||
// Returns the current position of the iterator.
|
||||
@@ -21,50 +21,40 @@ func (i Iterator[T]) Index() int {
|
||||
return i.index
|
||||
}
|
||||
|
||||
// Returns true if the iterator has no more items to iterate over.
|
||||
func (i Iterator[T]) IsDone() bool {
|
||||
return i.index == len(i.data)
|
||||
func (i Iterator[T]) Copy() *Iterator[T] {
|
||||
return &Iterator[T]{items: i.items, index: i.index}
|
||||
}
|
||||
|
||||
// Gets the next item in the slice, if one exists. Returns an error if there
|
||||
// isn't one.
|
||||
func (i Iterator[T]) Peek() (T, error) {
|
||||
var null T
|
||||
func (i *Iterator[T]) Sync(o *Iterator[T]) {
|
||||
i.index = o.index
|
||||
}
|
||||
|
||||
if i.IsDone() {
|
||||
// Create a new iterator, over a set of items.
|
||||
func (i Iterator[T]) Get() (T, error) {
|
||||
var null T
|
||||
if i.Done() {
|
||||
return null, fmt.Errorf("iterator is exhausted")
|
||||
}
|
||||
|
||||
return i.data[i.index], nil
|
||||
return i.items[i.index], nil
|
||||
}
|
||||
|
||||
// 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]) Pop() (T, error) {
|
||||
val, err := i.Peek()
|
||||
if err != nil {
|
||||
return val, err
|
||||
// Create a new iterator, over a set of items.
|
||||
func (i *Iterator[T]) Next() (T, error) {
|
||||
item, err := i.Get()
|
||||
if err == nil {
|
||||
i.index++
|
||||
}
|
||||
|
||||
i.index++
|
||||
return val, nil
|
||||
return item, err
|
||||
}
|
||||
|
||||
// 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
|
||||
// Create a new iterator, over a set of items.
|
||||
func (i *Iterator[T]) Back() {
|
||||
i.index = max(i.index-1, 0)
|
||||
}
|
||||
|
||||
// Returns the current position of the iterator.
|
||||
func (i Iterator[T]) Done() bool {
|
||||
return i.index == len(i.items)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user