diff --git a/Base.Tests/Structures/MaybeTests.cs b/Base.Tests/Structures/MaybeTests.cs new file mode 100644 index 0000000..4acf46a --- /dev/null +++ b/Base.Tests/Structures/MaybeTests.cs @@ -0,0 +1,45 @@ +using FruityFoundation.Base.Structures; +using NUnit.Framework; + +namespace Base.Tests.Structures; + +public class MaybeTests +{ + [Test] + public void TestBind_DoesNotBindEmptyValue() + { + var emptyMaybe = Maybe.Empty(); + + var result = emptyMaybe.Bind(x => Maybe.Just(x + 1)); + + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.False); + } + + [Test] + public void TestBind_BindsWhenHasValue() + { + var emptyMaybe = Maybe.Just(1); + + var result = emptyMaybe.Bind(x => Maybe.Just(x + 1)); + + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.True); + Assert.That(result.Value, Is.EqualTo(2)); + } + + [Test] + public void TestBind_BindsWhenHasValue_NewOutputType() + { + var maybe = Maybe.Just(25); + + var result = maybe.Bind(x => x switch + { + 25 => Maybe.Just("twenty-five"), + _ => Maybe.Empty() + }); + + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.True); + } +} diff --git a/Base/Structures/Maybe.cs b/Base/Structures/Maybe.cs index 5b375e3..d319b7c 100644 --- a/Base/Structures/Maybe.cs +++ b/Base/Structures/Maybe.cs @@ -54,7 +54,7 @@ public readonly struct Maybe public Maybe Map(Func transformer) => HasValue ? Maybe.Just(transformer(Value)) : Maybe.Empty(); - public Maybe Bind(Func binder) => + public Maybe Bind(Func> binder) => HasValue ? binder(Value) : Maybe.Empty(); public Maybe Cast()