github.com/m4gshm/gollections@v0.0.13-0.20240331203319-a34a86e58a24/loop/convert/api.go (about) 1 // Package convert provides loop converation helpers 2 package convert 3 4 import ( 5 "github.com/m4gshm/gollections/loop" 6 "github.com/m4gshm/gollections/op/check/not" 7 ) 8 9 // AndConvert - convert.AndConvert makes double converts From->Intermediate->To of the elements 10 func AndConvert[From, I, To any](next func() (From, bool), firsConverter func(From) I, secondConverter func(I) To) loop.Loop[To] { 11 return loop.Convert(next, func(from From) To { return secondConverter(firsConverter(from)) }) 12 } 13 14 // AndFilter - convert.AndFilter converts only filtered elements and returns them 15 func AndFilter[From, To any](next func() (From, bool), converter func(From) To, filter func(To) bool) loop.Loop[To] { 16 return loop.ConvertAndFilter(next, converter, filter) 17 } 18 19 // NotNil - convert.NotNil converts only not nil elements and returns them 20 func NotNil[From, To any](next func() (*From, bool), converter func(*From) To) loop.Loop[To] { 21 return loop.FilterAndConvert(next, not.Nil[From], converter) 22 } 23 24 // ToNotNil - convert.ToNotNil converts elements and returns only not nil converted elements 25 func ToNotNil[From, To any](next func() (From, bool), converter func(From) *To) loop.Loop[*To] { 26 return loop.ConvertCheck(next, func(f From) (*To, bool) { 27 if t := converter(f); t != nil { 28 return t, true 29 } 30 return nil, false 31 }) 32 } 33 34 // NilSafe - convert.NilSafe filters not nil next, converts that ones, filters not nils after converting and returns them 35 func NilSafe[From, To any](next func() (*From, bool), converter func(*From) *To) loop.Loop[*To] { 36 return loop.ConvertCheck(next, func(f *From) (*To, bool) { 37 if f != nil { 38 if t := converter(f); t != nil { 39 return t, true 40 } 41 } 42 return nil, false 43 }) 44 } 45 46 // Check - convert.Check is a short alias of loop.ConvertCheck 47 func Check[From, To any](next func() (From, bool), converter func(from From) (To, bool)) loop.Loop[To] { 48 return loop.ConvertCheck(next, converter) 49 } 50 51 // FromIndexed - convert.FromIndexed retrieves elements from a indexed source and converts them 52 func FromIndexed[From, To any](len int, next func(int) From, converter func(from From) To) loop.Loop[To] { 53 return loop.Convert(loop.OfIndexed(len, next), converter) 54 } 55 56 // AndReduce - convert.AndReduce converts elements and merge them into one 57 func AndReduce[From, To any](next func() (From, bool), converter func(From) To, merge func(To, To) To) (out To) { 58 return loop.ConvertAndReduce(next, converter, merge) 59 }