-
Notifications
You must be signed in to change notification settings - Fork 4
/
result.go
61 lines (53 loc) · 1.28 KB
/
result.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
59
60
61
package hoff
import (
"errors"
"strings"
)
// Result holds a result of a concurrent operation.
type Result[T any] struct {
Value T
Error error
}
// Results hold a sequence concurrent operation results in order.
type Results[T any] []Result[T]
// HasError returns whether the sequence of results has any errors.
func (rs Results[T]) HasError() bool {
for _, r := range rs {
if r.Error != nil {
return true
}
}
return false
}
// Values returns an array with the values of all non-error Results.
func (rs Results[T]) Values() (values []T) {
for _, result := range rs {
if result.Error == nil {
values = append(values, result.Value)
}
}
return values
}
// Errors returns an array with the errors of all non-valid Results.
func (rs Results[T]) Errors() (errors []error) {
for _, result := range rs {
if result.Error != nil {
errors = append(errors, result.Error)
}
}
return errors
}
// Error returns nil if the results contain no errors,
// or an error with the message a comma-separated string of all the errors in the collection.
func (rs Results[T]) Error() error {
errs := rs.Errors()
if len(errs) > 0 {
errorStrings := Map(
errs, func(err error) string {
return err.Error()
},
)
return errors.New(strings.Join(errorStrings, ", "))
}
return nil
}