-
Notifications
You must be signed in to change notification settings - Fork 0
/
supplier.go
50 lines (43 loc) · 1.25 KB
/
supplier.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
package fun
// Supplier represents a supplier of results or an error.
type Supplier func() (interface{}, error)
// SilentSupplier represents a supplier of results without returning an error.
// In case of an error it should just return the default value of the type.
type SilentSupplier func() interface{}
// ToSilentSupplier transforms Supplier into SilentSupplier
func (s Supplier) ToSilentSupplier() SilentSupplier {
return func() interface{} {
v, _ := s()
return v
}
}
// MustSupplier represents a supplier of results without returning an error.
// In case of an error it should panic with error value.
type MustSupplier func() interface{}
// ToMustSupplier transforms Supplier into MustSupplier
func (s Supplier) ToMustSupplier() MustSupplier {
return func() interface{} {
v, err := s()
if err != nil {
panic(err)
}
return v
}
}
// ToSupplier transforms MustSupplier into Supplier
func (ms MustSupplier) ToSupplier() Supplier {
return func() (v interface{}, err error) {
defer func() {
if r := recover(); r != nil {
err = r.(error)
}
}()
v = ms()
return
}
}
// ToSilentSupplier transforms MustSupplier into SilentSupplier
func (ms MustSupplier) ToSilentSupplier() SilentSupplier {
s := ms.ToSupplier()
return s.ToSilentSupplier()
}