Skip to content

Commit

Permalink
Merge pull request #29 from radyz/feat/add-option-or-operations
Browse files Browse the repository at this point in the history
feat: Support `Or` and `OrElse` operations on options.
  • Loading branch information
jeffijoe authored Feb 11, 2025
2 parents aaef39c + f9cd620 commit a3f69da
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/FxKit.Tests/UnitTests/Option/Option.MonadTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,17 @@ public void Associativity_ShouldHold()

#endregion

[Test]
public void Or_ShouldBeReturned()
{
var l = Option<int>.None;
var r = l.Or(1);
var rElse = l.OrElse(() => 2);

r.Should().BeSome(1);
rElse.Should().BeSome(2);
}

#region LINQ

[Test]
Expand Down
37 changes: 37 additions & 0 deletions src/FxKit/Option/Option.Monad.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,43 @@ public static Task<Option<U>> FlatMapAsync<T, U>(
? selector(value)
: Task.FromResult(Option<U>.None);

/// <summary>
/// Returns the source's Option if it contains a value, otherwise <paramref name="other" /> is returned.
/// </summary>
/// <remarks>
/// <paramref name="other" /> is eagerly evaluated; if the result of a function is being passed,
/// use <see cref="OrElse{T}" />.
/// </remarks>
/// <param name="source"></param>
/// <param name="other"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
[DebuggerHidden]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[GenerateTransformer]
public static Option<T> Or<T>(
this Option<T> source,
Option<T> other)
where T : notnull =>
source.TryGet(out _) ? source : other;

/// <summary>
/// Returns the source's Option if it contains a value, otherwise calls <paramref name="fallback" />
/// and returns the result.
/// </summary>
/// <param name="source"></param>
/// <param name="fallback"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
[DebuggerHidden]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[GenerateTransformer]
public static Option<T> OrElse<T>(
this Option<T> source,
Func<Option<T>> fallback)
where T : notnull =>
source.TryGet(out _) ? source : fallback();

#region LINQ

/// <inheritdoc cref="FlatMap{T,U}" />
Expand Down

0 comments on commit a3f69da

Please sign in to comment.