Skip to content

Commit

Permalink
fn: add Sink to Result
Browse files Browse the repository at this point in the history
  • Loading branch information
ProofOfKeags committed Nov 6, 2024
1 parent 5dec354 commit 9bbd327
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
10 changes: 10 additions & 0 deletions fn/result.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 26 additions & 0 deletions fn/result_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 9bbd327

Please sign in to comment.