Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support Or and OrElse operations on options. #29

Merged
merged 1 commit into from
Feb 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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