diff --git a/Base.Tests/Structures/MaybeTests.cs b/Base.Tests/Structures/MaybeTests.cs index 4acf46a..3a377c6 100644 --- a/Base.Tests/Structures/MaybeTests.cs +++ b/Base.Tests/Structures/MaybeTests.cs @@ -42,4 +42,52 @@ public class MaybeTests Assert.That(result, Is.InstanceOf>()); Assert.That(result.HasValue, Is.True); } + + [Test] + public void EmptyBind_DoesNotBindFactory_WhenHasValue() + { + var maybe = Maybe.Just(25); + + var result = maybe.EmptyBind(() => Maybe.Just(30)); + + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.True); + Assert.That(result.Value, Is.EqualTo(25)); + } + + [Test] + public void EmptyBind_BindsFactory_WhenDoesNotHaveValue() + { + var maybe = Maybe.Empty(); + + var result = maybe.EmptyBind(() => Maybe.Just(30)); + + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.True); + Assert.That(result.Value, Is.EqualTo(30)); + } + + [Test] + public void EmptyBind_DoesNotBindMaybe_WhenHasValue() + { + var maybe = Maybe.Just(25); + + var result = maybe.EmptyBind(Maybe.Just(30)); + + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.True); + Assert.That(result.Value, Is.EqualTo(25)); + } + + [Test] + public void EmptyBind_BindsMaybe_WhenDoesNotHaveValue() + { + var maybe = Maybe.Empty(); + + var result = maybe.EmptyBind(Maybe.Just(30)); + + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.True); + Assert.That(result.Value, Is.EqualTo(30)); + } } diff --git a/Base/Structures/Maybe.cs b/Base/Structures/Maybe.cs index d319b7c..6d06d0e 100644 --- a/Base/Structures/Maybe.cs +++ b/Base/Structures/Maybe.cs @@ -57,6 +57,12 @@ public readonly struct Maybe public Maybe Bind(Func> binder) => HasValue ? binder(Value) : Maybe.Empty(); + public Maybe EmptyBind(Func> maybeFactory) => + HasValue ? this : maybeFactory(); + + public Maybe EmptyBind(Maybe maybe) => + HasValue ? this : maybe; + public Maybe Cast() { if (!HasValue)