From b6f2ef3aa6318a25fe771ae8aa7c15eb476d6b07 Mon Sep 17 00:00:00 2001 From: Kyle Ratti Date: Fri, 3 May 2024 00:27:31 -0400 Subject: [PATCH] feat: add Maybe.TryParse --- Base.Tests/Structures/MaybeTests.cs | 29 +++++++++++++++++++++++++++++ Base/Structures/Maybe.cs | 10 ++++++++++ 2 files changed, 39 insertions(+) diff --git a/Base.Tests/Structures/MaybeTests.cs b/Base.Tests/Structures/MaybeTests.cs index e3a6791..8081c5b 100644 --- a/Base.Tests/Structures/MaybeTests.cs +++ b/Base.Tests/Structures/MaybeTests.cs @@ -485,4 +485,33 @@ public class MaybeTests // Assert Assert.That(result, Is.EqualTo("banana")); } + + [Test] + public void Maybe_Create_ReturnsEmptyValue_WhenTryParseFails() + { + // Arrange + const string input = "bananas"; + + // Act + var result = Maybe.TryParse(input, int.TryParse); + + // Assert + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.False); + } + + [Test] + public void Maybe_Create_ReturnsValue_WhenTryParseSucceeds() + { + // Arrange + const string input = "123"; + + // Act + var result = Maybe.TryParse(input, int.TryParse); + + // Assert + Assert.That(result, Is.InstanceOf>()); + Assert.That(result.HasValue, Is.True); + Assert.That(result.Value, Is.EqualTo(123)); + } } diff --git a/Base/Structures/Maybe.cs b/Base/Structures/Maybe.cs index 6233ea7..56fd9b2 100644 --- a/Base/Structures/Maybe.cs +++ b/Base/Structures/Maybe.cs @@ -2,6 +2,8 @@ namespace FruityFoundation.Base.Structures; using System; +public delegate bool TryParseDelegate(TInput input, out TOutput output); + public static class Maybe { public static Maybe Create(T value) => new(value); @@ -11,6 +13,14 @@ public static class Maybe ? Empty() : new Maybe(value); + public static Maybe TryParse(TInput value, TryParseDelegate tryParse) + { + if (!tryParse(value, out var output)) + return Empty(); + + return new Maybe(output); + } + public static Maybe Empty() => new(); }