-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresults.go
58 lines (48 loc) · 1.23 KB
/
results.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package parallel
import "errors"
// Result represents a result from a parallel task execution
type Result struct {
Value interface{}
Error error
}
// FilterErrors returns only the successful results and aggregates errors
func FilterErrors(results []interface{}) ([]interface{}, []error) {
var (
validResults []interface{}
errs []error
)
for _, result := range results {
if err, ok := result.(error); ok {
errs = append(errs, err)
} else {
validResults = append(validResults, result)
}
}
return validResults, errs
}
// CombineErrors combines multiple errors into a single error
func CombineErrors(errs []error) error {
if len(errs) == 0 {
return nil
}
errStr := "multiple errors occurred:"
for _, err := range errs {
errStr += "\n - " + err.Error()
}
return errors.New(errStr)
}
// MapResults applies a transformation function to successful results
func MapResults[T, R any](results []interface{}, mapper func(T) R) ([]R, []error) {
var (
transformed []R
errs []error
)
for _, result := range results {
if err, ok := result.(error); ok {
errs = append(errs, err)
} else if val, ok := result.(T); ok {
transformed = append(transformed, mapper(val))
}
}
return transformed, errs
}