feat: T?.AsMaybe() for reference types

This commit is contained in:
Kyle Ratti 2023-12-24 21:11:25 -05:00
parent 1d2a15189b
commit 572c365725
No known key found for this signature in database
GPG Key ID: 4D429B6287C68DD9
2 changed files with 48 additions and 1 deletions

View File

@ -1,4 +1,5 @@
using FruityFoundation.Base.Structures; using System.Linq;
using FruityFoundation.Base.Structures;
using NUnit.Framework; using NUnit.Framework;
namespace Base.Tests.Structures; namespace Base.Tests.Structures;
@ -12,4 +13,47 @@ public class NullableExtensionTests
[Test] [Test]
public void TestNullableStructOfValueToMaybe() => public void TestNullableStructOfValueToMaybe() =>
Assert.AreEqual(Maybe.Just(25), ((int?)25).ToMaybe()); Assert.AreEqual(Maybe.Just(25), ((int?)25).ToMaybe());
[Test]
public void TestNullableReferenceOfNullAsMaybe()
{
string? nullableString = null;
var result = nullableString.AsMaybe();
Assert.That(result, Is.InstanceOf<Maybe<string>>());
Assert.That(result.HasValue, Is.False);
}
[Test]
public void TestNullableReferenceOfValueAsMaybe()
{
string? nullableString = "banana";
var result = nullableString.AsMaybe();
Assert.That(result, Is.InstanceOf<Maybe<string>>());
Assert.That(result.HasValue, Is.True);
Assert.That(result.Value, Is.EqualTo("banana"));
}
[Test]
public void TestNullableReferenceAsMaybeWorksWithChoose()
{
string?[] stringCollection =
[
"banana",
"bob",
null
];
var result = stringCollection
.Choose(x => x.AsMaybe())
.ToArray();
Assert.That(result, Is.InstanceOf<string[]>());
Assert.That(result, Has.Length.EqualTo(2));
Assert.That(result[0], Is.EqualTo("banana"));
Assert.That(result[1], Is.EqualTo("bob"));
}
} }

View File

@ -4,4 +4,7 @@ public static class NullableExtensions
{ {
public static Maybe<T> ToMaybe<T>(this T? item) where T : struct => public static Maybe<T> ToMaybe<T>(this T? item) where T : struct =>
item ?? Maybe.Empty<T>(); item ?? Maybe.Empty<T>();
public static Maybe<T> AsMaybe<T>(this T? item) where T : class =>
item ?? Maybe.Empty<T>();
} }