fn: add Sink to Result

This commit is contained in:
Keagan McClelland 2024-08-14 15:22:30 -07:00
parent 5dec35426c
commit 9bbd327a10
No known key found for this signature in database
GPG Key ID: FA7E65C951F12439
2 changed files with 36 additions and 0 deletions

View File

@ -224,6 +224,16 @@ func AndThen2[A, B, C any](ra Result[A], rb Result[B],
})
}
// Sink consumes a Result, either propagating its error or processing its
// success value with a function that can fail.
func (r Result[A]) Sink(f func(A) error) error {
if r.IsErr() {
return r.right
}
return f(r.left)
}
// TransposeResOpt transposes the Result[Option[A]] into a Option[Result[A]].
// This has the effect of leaving an A value alone while inverting the Result
// and Option layers. If there is no internal A value, it will convert the

View File

@ -70,3 +70,29 @@ func TestPropTransposeResOptInverts(t *testing.T) {
require.NoError(t, quick.Check(f, nil))
}
func TestSinkOnErrNoContinutationCall(t *testing.T) {
called := false
res := Err[uint8](errors.New("err")).Sink(
func(a uint8) error {
called = true
return nil
},
)
require.False(t, called)
require.NotNil(t, res)
}
func TestSinkOnOkContinuationCall(t *testing.T) {
called := false
res := Ok(uint8(1)).Sink(
func(a uint8) error {
called = true
return nil
},
)
require.True(t, called)
require.Nil(t, res)
}