feat: add Maybe.TryParse

This commit is contained in:
Kyle Ratti 2024-05-03 00:27:31 -04:00
parent b07f31f75f
commit b6f2ef3aa6
No known key found for this signature in database
GPG Key ID: 4D429B6287C68DD9
2 changed files with 39 additions and 0 deletions

View File

@ -485,4 +485,33 @@ public class MaybeTests
// Assert // Assert
Assert.That(result, Is.EqualTo("banana")); Assert.That(result, Is.EqualTo("banana"));
} }
[Test]
public void Maybe_Create_ReturnsEmptyValue_WhenTryParseFails()
{
// Arrange
const string input = "bananas";
// Act
var result = Maybe.TryParse<string, int>(input, int.TryParse);
// Assert
Assert.That(result, Is.InstanceOf<Maybe<int>>());
Assert.That(result.HasValue, Is.False);
}
[Test]
public void Maybe_Create_ReturnsValue_WhenTryParseSucceeds()
{
// Arrange
const string input = "123";
// Act
var result = Maybe.TryParse<string, int>(input, int.TryParse);
// Assert
Assert.That(result, Is.InstanceOf<Maybe<int>>());
Assert.That(result.HasValue, Is.True);
Assert.That(result.Value, Is.EqualTo(123));
}
} }

View File

@ -2,6 +2,8 @@ namespace FruityFoundation.Base.Structures;
using System; using System;
public delegate bool TryParseDelegate<in TInput, TOutput>(TInput input, out TOutput output);
public static class Maybe public static class Maybe
{ {
public static Maybe<T> Create<T>(T value) => new(value); public static Maybe<T> Create<T>(T value) => new(value);
@ -11,6 +13,14 @@ public static class Maybe
? Empty<T>() ? Empty<T>()
: new Maybe<T>(value); : new Maybe<T>(value);
public static Maybe<TOutput> TryParse<TInput, TOutput>(TInput value, TryParseDelegate<TInput, TOutput> tryParse)
{
if (!tryParse(value, out var output))
return Empty<TOutput>();
return new Maybe<TOutput>(output);
}
public static Maybe<T> Empty<T>() => new(); public static Maybe<T> Empty<T>() => new();
} }