2023-10-15 02:21:00 +02:00
|
|
|
package shared
|
|
|
|
|
|
|
|
import "sync"
|
|
|
|
|
2024-02-05 07:19:11 +01:00
|
|
|
func ForEach[T any](arr []T, numThreads int, fn func(T) error) error {
|
2023-10-15 02:21:00 +02:00
|
|
|
wg := &sync.WaitGroup{}
|
2024-02-05 07:19:11 +01:00
|
|
|
wg.Add(len(arr))
|
|
|
|
|
2023-10-15 02:21:00 +02:00
|
|
|
limiter := make(chan bool, numThreads)
|
2024-02-05 07:19:11 +01:00
|
|
|
|
2023-10-15 02:21:00 +02:00
|
|
|
var errors []error
|
2024-02-05 07:19:11 +01:00
|
|
|
for _, item := range arr {
|
2023-10-15 02:21:00 +02:00
|
|
|
limiter <- true
|
|
|
|
go func(x T) {
|
|
|
|
defer wg.Done()
|
|
|
|
err := fn(x)
|
|
|
|
if err != nil {
|
|
|
|
errors = append(errors, err)
|
|
|
|
}
|
|
|
|
<-limiter
|
|
|
|
}(item)
|
2024-02-05 07:19:11 +01:00
|
|
|
if len(errors) > 0 {
|
|
|
|
return errors[0]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-15 02:21:00 +02:00
|
|
|
wg.Wait()
|
|
|
|
if len(errors) > 0 {
|
|
|
|
return errors[0]
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|