feat: add Maybe.TryParse
This commit is contained in:
parent
b07f31f75f
commit
b6f2ef3aa6
|
@ -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));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -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();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user