From f9cd6204595927feb4b1211428af0c79723e5df1 Mon Sep 17 00:00:00 2001 From: Ernesto Chavez Date: Tue, 11 Feb 2025 10:36:17 -0600 Subject: [PATCH] feat: Support `Or` and `OrElse` operations on options. --- .../UnitTests/Option/Option.MonadTests.cs | 11 ++++++ src/FxKit/Option/Option.Monad.cs | 37 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/FxKit.Tests/UnitTests/Option/Option.MonadTests.cs b/src/FxKit.Tests/UnitTests/Option/Option.MonadTests.cs index 2e0cb29..b123c1a 100644 --- a/src/FxKit.Tests/UnitTests/Option/Option.MonadTests.cs +++ b/src/FxKit.Tests/UnitTests/Option/Option.MonadTests.cs @@ -95,6 +95,17 @@ public void Associativity_ShouldHold() #endregion + [Test] + public void Or_ShouldBeReturned() + { + var l = Option.None; + var r = l.Or(1); + var rElse = l.OrElse(() => 2); + + r.Should().BeSome(1); + rElse.Should().BeSome(2); + } + #region LINQ [Test] diff --git a/src/FxKit/Option/Option.Monad.cs b/src/FxKit/Option/Option.Monad.cs index 062d7a3..7e3c1ea 100644 --- a/src/FxKit/Option/Option.Monad.cs +++ b/src/FxKit/Option/Option.Monad.cs @@ -50,6 +50,43 @@ public static Task> FlatMapAsync( ? selector(value) : Task.FromResult(Option.None); + /// + /// Returns the source's Option if it contains a value, otherwise is returned. + /// + /// + /// is eagerly evaluated; if the result of a function is being passed, + /// use . + /// + /// + /// + /// + /// + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [GenerateTransformer] + public static Option Or( + this Option source, + Option other) + where T : notnull => + source.TryGet(out _) ? source : other; + + /// + /// Returns the source's Option if it contains a value, otherwise calls + /// and returns the result. + /// + /// + /// + /// + /// + [DebuggerHidden] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [GenerateTransformer] + public static Option OrElse( + this Option source, + Func> fallback) + where T : notnull => + source.TryGet(out _) ? source : fallback(); + #region LINQ ///