Compare commits

...

4 Commits

Author SHA1 Message Date
78436e629c FlatMap function introduced 2024-05-10 20:32:41 +02:00
4612cb74b2 refactored result wrapper func names 2024-04-04 19:13:43 +02:00
faf75185ae refactor 2024-04-04 19:11:33 +02:00
3dfcee4ee4 fixed Get and GetUnsafe methods for Result struct 2024-04-04 19:07:52 +02:00
2 changed files with 25 additions and 7 deletions

15
flat.go
View File

@ -15,6 +15,21 @@ func FlatSlice[T any](source <-chan []T) <-chan T {
return out
}
func FlatMap[K comparable, V, T any](source <-chan map[K]V, unmapper func(key K, value V) T) <-chan T {
out := make(chan T, cap(source))
go func() {
defer close(out)
for slice := range source {
for k, v := range slice {
out <- unmapper(k, v)
}
}
}()
return out
}
func FlatChan[T any](source <-chan <-chan T) <-chan T {
out := make(chan T, cap(source))

View File

@ -13,12 +13,12 @@ func ResultOf[T any](value T, err error) Result[T] {
return Result[T]{value: &value, err: nil}
}
func WrapMapFunc[I, O any](f func(I) (O, error)) func(I) Result[O] {
func WrapResultOutputFunc[I, O any](f func(I) (O, error)) func(I) Result[O] {
return func(i I) Result[O] { return ResultOf(f(i)) }
}
func WrapMapResultFunc[I, O any](f func(I) (O, error)) func(Result[I]) Result[O] {
resFunc := WrapMapFunc(f)
func WrapResultFunc[I, O any](f func(I) (O, error)) func(Result[I]) Result[O] {
resFunc := WrapResultOutputFunc(f)
nilValue := *new(O)
return func(r Result[I]) Result[O] {
v, err := r.Get()
@ -46,10 +46,13 @@ func (r Result[T]) GetOrDefault(defaultValue T) T {
}
func (r Result[T]) Get() (T, error) {
if r.err != nil {
return *new(T), r.err
}
return *r.value, r.err
}
func (r Result[T]) GetSafe() T {
func (r Result[T]) GetUnsafe() T {
if r.err != nil {
panic(r.err)
}
@ -61,7 +64,7 @@ func (r Result[T]) Err() error {
}
func FilterSuccess[T any](source <-chan Result[T]) <-chan T {
succeeded := Filter(source, func(r Result[T]) bool { return r.Success() })
succeeded := Filter(source, Result[T].Success)
return MapSuccessive(succeeded, func(r Result[T]) T {
v, _ := r.Get()
@ -70,7 +73,7 @@ func FilterSuccess[T any](source <-chan Result[T]) <-chan T {
}
func FilterFail[T any](source <-chan Result[T]) <-chan T {
failed := Filter(source, func(r Result[T]) bool { return r.Fail() })
failed := Filter(source, Result[T].Fail)
return MapSuccessive(failed, func(r Result[T]) T {
v, _ := r.Get()
@ -91,7 +94,7 @@ func FilterResults[T any](source <-chan Result[T]) (succeeded <-chan T, failed <
fail <- r.Err()
continue
}
succ <- r.GetSafe()
succ <- r.GetUnsafe()
}
}()