Skip to content

Commit bf72b0e

Browse files
committed
fn+rpcserver+supplysync: create re-usable helper functions
1 parent 3f5f816 commit bf72b0e

File tree

3 files changed

+189
-346
lines changed

3 files changed

+189
-346
lines changed

fn/func.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,29 @@ func MapErr[I, O any, S []I](s S, f func(I) (O, error)) ([]O, error) {
9393
return output, nil
9494
}
9595

96+
// MapErrWithPtr applies the given fallible mapping function to each element of
97+
// the given slice and generates a new slice. This is identical to MapErr, but
98+
// can be used when the callback returns a pointer, and returns early if any
99+
// single mapping fails.
100+
func MapErrWithPtr[I, O any, S []I](s S, f func(I) (*O, error)) ([]O, error) {
101+
output := make([]O, len(s))
102+
for i, x := range s {
103+
outPtr, err := f(x)
104+
if err != nil {
105+
return nil, err
106+
}
107+
108+
if outPtr == nil {
109+
return nil, fmt.Errorf("nil pointer returned for "+
110+
"item %d", i)
111+
}
112+
113+
output[i] = *outPtr
114+
}
115+
116+
return output, nil
117+
}
118+
96119
// FlatMapErr applies the given mapping function to each element of the given
97120
// slice, concatenates the results into a new slice, and returns an error if
98121
// the mapping function fails.

0 commit comments

Comments
 (0)