Skip to content

Commit

Permalink
feat: implement Match on Result with void return type (#417)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tr00d authored Jun 8, 2023
1 parent da9075a commit 58975cc
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
20 changes: 20 additions & 0 deletions Vonage.Common.Test/Monads/ResultTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,26 @@ public async Task MapAsync_ShouldReturnSuccess_GivenValueIsSuccess() =>
.Should()
.BeSuccess(6);

[Fact]
public void Match_ShouldExecuteFailureOperation_GivenValueIsSuccess()
{
var value = 0;
void Success(int a) => value++;
void Failure(IResultFailure failure) => value--;
CreateFailure().Match(Success, Failure);
value.Should().Be(-1);
}

[Fact]
public void Match_ShouldExecuteSuccessOperation_GivenValueIsSuccess()
{
var value = 0;
void Success(int a) => value++;
void Failure(IResultFailure failure) => value--;
CreateSuccess(5).Match(Success, Failure);
value.Should().Be(1);
}

[Fact]
public void Match_ShouldReturnFailureOperation_GivenValueIsFailure() =>
CreateFailure()
Expand Down
17 changes: 17 additions & 0 deletions Vonage.Common/Monads/Result.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,23 @@ public async Task<Result<TB>> MapAsync<TB>(Func<T, Task<TB>> map) =>
public TB Match<TB>(Func<T, TB> successOperation, Func<IResultFailure, TB> failureOperation) =>
this.IsFailure ? failureOperation(this.failure) : successOperation(this.success);

/// <summary>
/// Match the two states of the Result.
/// </summary>
/// <param name="successOperation">Success match operation.</param>
/// <param name="failureOperation">Failure match operation.</param>
public void Match(Action<T> successOperation, Action<IResultFailure> failureOperation)
{
if (this.IsFailure)
{
failureOperation(this.failure);
}
else
{
successOperation(this.success);
}
}

/// <summary>
/// Merge two results together. The merge operation will be used if they're both in a Success state.
/// </summary>
Expand Down

0 comments on commit 58975cc

Please sign in to comment.