lambda/parallel/map.go

84 lines
1.6 KiB
Go
Raw Permalink Normal View History

2022-03-26 22:22:54 +00:00
package parallel
import (
"sync"
"git.tuxpa.in/a/lambda"
)
2022-03-27 01:44:39 +00:00
func Map[T any](xs []T, fx func(T) T, n ...int) []T {
rc := routineCount
if len(n) > 0 {
rc = n[0]
}
spl := lambda.Split(xs, rc)
2022-03-26 22:22:54 +00:00
wg := new(sync.WaitGroup)
wg.Add(len(spl))
for i, v := range spl {
go func(ix int, vx []T) {
spl[ix] = lambda.Map(vx, fx)
wg.Done()
}(i, v)
}
wg.Wait()
return lambda.Flatten(spl)
}
2022-03-27 01:44:39 +00:00
func MapV[T, V any](xs []T, fx func(T) V, n ...int) []V {
rc := routineCount
if len(n) > 0 {
rc = n[0]
}
spl := lambda.Split(xs, rc)
2022-03-26 22:22:54 +00:00
wg := new(sync.WaitGroup)
wg.Add(len(spl))
tmp := make([][]V, len(spl))
for i, v := range spl {
go func(ix int, vx []T) {
2022-03-27 01:19:04 +00:00
tmp[ix] = lambda.MapV(vx, fx)
2022-03-26 22:22:54 +00:00
wg.Done()
}(i, v)
}
wg.Wait()
return lambda.Flatten(tmp)
}
2022-03-27 01:44:39 +00:00
func MapError[T any](xs []T, fx func(T) (T, error), n ...int) ([]T, []error) {
rc := routineCount
if len(n) > 0 {
rc = n[0]
}
spl := lambda.Split(xs, rc)
wg := new(sync.WaitGroup)
wg.Add(len(spl))
tmp := make([][]error, len(spl))
for i, v := range spl {
go func(ix int, vx []T) {
spl[ix], tmp[ix] = lambda.MapError(vx, fx)
wg.Done()
}(i, v)
}
wg.Wait()
return lambda.Flatten(spl), lambda.Flatten(tmp)
}
func MapErrorV[T, V any](xs []T, fx func(T) (V, error), n ...int) ([]V, []error) {
rc := routineCount
if len(n) > 0 {
rc = n[0]
}
spl := lambda.Split(xs, rc)
wg := new(sync.WaitGroup)
wg.Add(len(spl))
tmp := make([][]V, len(spl))
tmp2 := make([][]error, len(spl))
for i, v := range spl {
go func(ix int, vx []T) {
tmp[ix], tmp2[ix] = lambda.MapErrorV(vx, fx)
wg.Done()
}(i, v)
}
wg.Wait()
return lambda.Flatten(tmp), lambda.Flatten(tmp2)
}