From 8e007975f66d83b9d3435149db361ae975ff0f91 Mon Sep 17 00:00:00 2001 From: Kyle Ratti Date: Mon, 25 Dec 2023 14:37:58 -0500 Subject: [PATCH] feat: Maybe.EmptyBind --- Base.Tests/Structures/MaybeTests.cs | 48 +++++++++++++++++++++++++++++ Base/Structures/Maybe.cs | 6 ++++ 2 files changed, 54 insertions(+) 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)