iterator

package module
v0.0.0-...-61f18e5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 1, 2024 License: MIT Imports: 3 Imported by: 0

README

iterator

Golang implementation of a generic iterator. Inspiration comes from the bufio.Scanner type. The major advantage of an iterator is in lazy evaluation of the elements.

The Basics

Iterator Interface

The core interface that this package defines is Iterator. Its three methods are:

  • Next to prepare the next element.
  • Get to return the current element.
  • Err to report any errors that might have occurred.
Iterators and Slices

This package includes tools for converting between slices and iterators when necessary.

The Slice type is a wrapper of a slice that implements Iterator.

The ToSlice function returns slice representation of an Iterator.

Example:

package main

import "github.com/ruesier/iterator"

func main() {
    data := []int{1, 2, 3, 4, 5}
    sliceIter := &Slice[int]{
        Data: data,
    }

    result, err := iterator.ToSlice(sliceIter)
    if err != nil {
        log.Fatal(err)
    }
    for i, d := range data {
        if d != result[i] {
            log.Fatalf("mismatched result expected %d at index %d, got %d", d, i, result[i])
        }
    }
}
Transformations

The Filter, Map, and Limit types wrap iterators to produce new iterators.

  • Filter only returns values that pass a provided test function
  • Map applies an update function to each element
  • Limit only returns a maximum number of elements

Async Iteration

Documentation

Overview

Package iterator defines an interface to represent lazy iteration of values. Also includes types and functions for interacting with iterators.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func All

func All[E any](iter Iterator[E], predicate func(E) bool) (bool, error)

func Any

func Any[E any](iter Iterator[E], predicate func(E) bool) (bool, error)

func Fold

func Fold[ELEMENT any, RESULT any](iter Iterator[ELEMENT], fold func(ELEMENT, RESULT) (RESULT, error), init RESULT) (RESULT, error)

Fold uses the provided function to update the result with each element from the iterator. Returns the final result.

func Reduce

func Reduce[ELEMENT any](iter Iterator[ELEMENT], reduce func(ELEMENT, ELEMENT) (ELEMENT, error)) (ELEMENT, error)

Reduce applies the provided functions to each element in the iterator along with an acculator of the same type.

func SendToChannel

func SendToChannel[E any](iter Iterator[E], c chan Result[E])

func ToSlice

func ToSlice[E any](iter Iterator[E]) (result []E, err error)

ToSlice reads all the values from an iterator and returns them all. If Iterator returns an infinite number of values this will result in an infinite loop. Use an `iterator.Limit` to prevent infinite loops.

Types

type Channel

type Channel[E any] interface {
	Send(E) bool
	SendErr(error) bool
}

type Clonable

type Clonable[E any] interface {
	Clone() E
}

Clonable types are able to return a copy of themselves. Usually this copy has newly allocated space for all the mutable components.

type CloneNoOp

type CloneNoOp[E any] struct {
	Wrap E
}

CloneNoOp breaks the convention of the Clonable type by having Clone just return the same value. This is to allow convenient use of the Echo iterator without needing to implement `Clone`. Warning: Reference types will preserve transformations.

func (CloneNoOp[E]) Clone

func (c CloneNoOp[E]) Clone() E

type Combine

type Combine[BEFORE any, AFTER any] struct {
	Iterators []Iterator[BEFORE]
	Join      func(...BEFORE) AFTER
}

func (Combine[BEFORE, AFTER]) Err

func (c Combine[BEFORE, AFTER]) Err() error

func (Combine[BEFORE, AFTER]) Get

func (c Combine[BEFORE, AFTER]) Get() AFTER

func (Combine[BEFORE, AFTER]) Next

func (c Combine[BEFORE, AFTER]) Next() bool

type Echo

type Echo[E any] struct {
	Template Clonable[E]
}

Echo returns a clone of the same data repeatedly.

func (Echo[E]) Err

func (e Echo[E]) Err() error

func (Echo[E]) Get

func (e Echo[E]) Get() E

func (Echo[E]) Next

func (e Echo[E]) Next() bool

type Empty

type Empty[E any] struct{}

func (Empty[E]) Err

func (e Empty[E]) Err() error

func (Empty[E]) Get

func (e Empty[E]) Get() E

func (Empty[E]) Next

func (e Empty[E]) Next() bool

type Error

type Error string
const Stop Error = "Stop Iteration"

func (Error) Error

func (e Error) Error() string

type Filter

type Filter[E any] struct {
	Iterator[E]
	// Test should return true if the provided value should be included.
	Test func(E) bool
}

Filter is an Iterator that wraps another iterator. It only returns the values that the Test function returns true for.

func (Filter[E]) Next

func (f Filter[E]) Next() bool

type FilterMap

type FilterMap[BEFORE any, AFTER any] struct {
	Iterator[BEFORE]

	TestUpdate func(BEFORE) (bool, AFTER)
	// contains filtered or unexported fields
}

func (FilterMap[BEFORE, AFTER]) Get

func (fm FilterMap[BEFORE, AFTER]) Get() AFTER

func (FilterMap[BEFORE, AFTER]) Next

func (fm FilterMap[BEFORE, AFTER]) Next() bool

type Generate

type Generate[E any] func(E) (E, error)

Generate is the function used by Generator to create the next value. The parameter is the previous value returned by the iterator. The first call to Generate will be passed the zero value of E. The returns should have the following valid structures - return some_value, nil. Continue iterating, some_value will be the next Get Value - return zero_of_E, some_error. An error occurred during Generate, Iteration Error. - return zero_of_E, Stop. Iteration is finished.

type Generator

type Generator[E any] struct {
	Generate Generate[E]
	// contains filtered or unexported fields
}

func (*Generator[E]) Err

func (g *Generator[E]) Err() error

func (*Generator[E]) Get

func (g *Generator[E]) Get() E

func (*Generator[E]) Next

func (g *Generator[E]) Next() bool

type Iterator

type Iterator[E any] interface {
	// Next returns true when there is a value to be accessed with Get.
	// False either means that the Iterator is empty or an error occurred.
	Next() bool
	// Get returns the current value of the Iterator. Get should return the same
	// value until Next is called. Get's behavior is undefined if called before
	// Next or when Next returns false.
	Get() E
	// Err returns any errors occurred. if Next returns true, this should return nil
	Err() error
}

Iterator is the primary interface this package defines. The basic usage of an Iterator looks like this.

```golang

for iter.Next() {
	doSomething(iter.Get())
}
if err := iter.Err(); err != nil {
	panic(err)
}

````

func MapAsync

func MapAsync[BEFORE any, AFTER any](iter Iterator[BEFORE], update func(BEFORE) (AFTER, error), n int) Iterator[AFTER]

MapAsync applies the update function inside a separate go routines.

func NewChannelIterator

func NewChannelIterator[E any](_ctx context.Context, generators ...func(Channel[E])) Iterator[E]

func Range

func Range[NUM constraints.Integer | constraints.Float](vals ...NUM) Iterator[NUM]

Range returns an iterator from a start number to an end number, not including the end value. Range interprets the number of parameters as follows: - Range() => empty Iterator, Next will return false. - Range(end) => an Iterator over 0 <= val < end, step = 1. - Range(start, end) => an Iterator over start <= val < end, step = 1. - Range(start, end, step) => an Iterator over start <= val < end, by the step value. any parameters past the first 3 are ignored.

type Limit

type Limit[E any] struct {
	Iterator[E]
	Max int
	// contains filtered or unexported fields
}

func (*Limit[E]) Next

func (l *Limit[E]) Next() bool

type Map

type Map[BEFORE any, AFTER any] struct {
	Iterator[BEFORE]
	Update func(BEFORE) AFTER
}

Map is an Iterator that wraps another iterator. It applies the Convert function to each value. This can result in a change in the iterating type.

func (Map[BEFORE, AFTER]) Get

func (m Map[BEFORE, AFTER]) Get() AFTER

type Result

type Result[E any] struct {
	Value E
	Err   error
}

type Slice

type Slice[E any] struct {
	Slice []E
	// contains filtered or unexported fields
}

Slice is a wrapper of a slice that implements the Iterator interface.

func (*Slice[E]) Err

func (s *Slice[E]) Err() error

func (*Slice[E]) Get

func (s *Slice[E]) Get() E

func (*Slice[E]) Next

func (s *Slice[E]) Next() bool

type StopWhen

type StopWhen[E any] struct {
	Iterator[E]
	When func(E) bool
	// contains filtered or unexported fields
}

func (*StopWhen[E]) Get

func (sw *StopWhen[E]) Get() E

func (*StopWhen[E]) Next

func (sw *StopWhen[E]) Next() bool

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL