github.com/m4gshm/gollections@v0.0.10/break/kv/loop/filter.go (about) 1 package loop 2 3 import ( 4 "github.com/m4gshm/gollections/break/kv" 5 "github.com/m4gshm/gollections/break/loop" 6 ) 7 8 // FiltIter is the KVIterator wrapper that provides filtering of key/value elements by a Predicate. 9 type FiltIter[K, V any] struct { 10 next func() (K, V, bool, error) 11 filter func(K, V) (bool, error) 12 } 13 14 var ( 15 _ kv.Iterator[any, any] = (*FiltIter[any, any])(nil) 16 _ kv.Iterator[any, any] = FiltIter[any, any]{} 17 ) 18 19 var _ kv.IterFor[any, any, FiltIter[any, any]] = FiltIter[any, any]{} 20 21 // Track takes key, value pairs retrieved by the iterator. Can be interrupt by returning ErrBreak 22 func (f FiltIter[K, V]) Track(traker func(key K, value V) error) error { 23 return loop.Track(f.Next, traker) 24 } 25 26 // Next returns the next key/value pair. 27 // The ok result indicates whether the pair was returned by the iterator. 28 // If ok == false, then the iteration must be completed. 29 func (f FiltIter[K, V]) Next() (key K, value V, ok bool, err error) { 30 if !(f.next == nil || f.filter == nil) { 31 key, value, ok, err = nextFiltered(f.next, f.filter) 32 } 33 return key, value, ok, err 34 } 35 36 // Start is used with for loop construct like 'for i, k, v, ok, err := i.Start(); ok || err != nil ; k, v, ok, err = i.Next() { if err != nil { return err }}' 37 func (f FiltIter[K, V]) Start() (FiltIter[K, V], K, V, bool, error) { 38 return startKvIt[K, V](f) 39 } 40 41 func nextFiltered[K any, V any](next func() (K, V, bool, error), filter func(K, V) (bool, error)) (key K, val V, filtered bool, err error) { 42 return Firstt(next, filter) 43 }