-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbelt.go
More file actions
86 lines (77 loc) · 1.86 KB
/
belt.go
File metadata and controls
86 lines (77 loc) · 1.86 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright 2020 Javad M. Amiri. All rights reserved. MIT license.
package orrer
import "sync"
type (
Fn func() (interface{}, error)
FnArg func(interface{}) (interface{}, error)
)
// GetAny returns an error if either of errors passed to it is not nil. Otherwise the return value would be nil.
func GetAny(errors ...error) error {
for _, err := range errors {
if err != nil {
return err
}
}
return nil
}
// GetValsOrError runs a series of functions; in case any of functions return an error, it will be returned, otherwise
// results is returned in an array
func GetValsOrError(fns ...Fn) ([]interface{}, error) {
res := make([]interface{}, len(fns))
for idx, fn := range fns {
val, err := fn()
if err != nil {
return nil, err
}
res[idx] = val
}
return res, nil
}
// GoGetValsOrError runs a series of functions concurrently; in case any of the passed functions return an error,
// it will be returned, otherwise the results is returned in an array
func GoGetValsOrError(fns ...Fn) ([]interface{}, error) {
res := make([]interface{}, len(fns))
errCh := make(chan error)
doneCh := make(chan struct{})
wg := sync.WaitGroup{}
for idx, fn := range fns {
wg.Add(1)
go func(i int, toRun Fn) {
val, err := toRun()
if err != nil {
errCh <- err
return
}
res[i] = val
wg.Done()
}(idx, fn)
}
go func() {
wg.Wait()
close(doneCh)
}()
for {
select {
case err := <-errCh:
return nil, err
case <-doneCh:
return res, nil
}
}
}
// GetSeriesOrError runs a series of functions passing the returning value of first one to the second and so on.
func GetSeriesOrError(kickOff interface{}, fns ...FnArg) (interface{}, error) {
var val interface{}
var err error
for idx, fn := range fns {
if idx == 0 {
val, err = fn(kickOff)
continue
}
val, err = fn(val)
if err != nil {
return nil, err
}
}
return val, nil
}