github.com/m4gshm/gollections@v0.0.10/kv/loop/convert.go (about) 1 package loop 2 3 import ( 4 "github.com/m4gshm/gollections/kv" 5 "github.com/m4gshm/gollections/loop" 6 ) 7 8 // ConvertIter is the iterator wrapper implementation applying a converter to all iterable key/value elements. 9 type ConvertIter[K, V any, K2, V2 any, C func(K, V) (K2, V2)] struct { 10 next func() (K, V, bool) 11 converter C 12 } 13 14 var ( 15 _ kv.Iterator[any, any] = (*ConvertIter[any, any, any, any, func(any, any) (any, any)])(nil) 16 _ kv.Iterator[any, any] = ConvertIter[any, any, any, any, func(any, any) (any, any)]{} 17 ) 18 19 var _ kv.IterFor[any, any, ConvertIter[any, any, any, any, func(any, any) (any, any)]] = (*ConvertIter[any, any, any, any, func(any, any) (any, any)])(nil) 20 21 // Track takes key, value pairs retrieved by the iterator. Can be interrupt by returning ErrBreak 22 func (i ConvertIter[K, V, K2, V2, C]) Track(traker func(key K2, value V2) error) error { 23 return loop.Track(i.Next, traker) 24 } 25 26 // TrackEach takes all key, value pairs retrieved by the iterator 27 func (i ConvertIter[K, V, K2, V2, C]) TrackEach(traker func(key K2, value V2)) { 28 loop.TrackEach(i.Next, traker) 29 } 30 31 // Next returns the next key/value pair. 32 // The ok result indicates whether an pair was returned by the iterator. 33 // If ok == false, then the iteration must be completed. 34 func (i ConvertIter[K, V, K2, V2, C]) Next() (k2 K2, v2 V2, ok bool) { 35 if next := i.next; next != nil { 36 if K, V, ok := next(); ok { 37 k2, v2 = i.converter(K, V) 38 return k2, v2, true 39 } 40 } 41 return k2, v2, false 42 } 43 44 // Start is used with for loop construct like 'for i, k, v, ok := i.Start(); ok; k, v, ok = i.Next() { }' 45 func (i ConvertIter[K, V, K2, V2, C]) Start() (ConvertIter[K, V, K2, V2, C], K2, V2, bool) { 46 return startKvIt[K2, V2](i) 47 }