feat: IEnumerable<T>.ConditionalAppend(Maybe<T>)

This commit is contained in:
Kyle Ratti 2023-12-24 22:35:59 -05:00
parent b59b5655bf
commit de8d2f393c
No known key found for this signature in database
GPG Key ID: 4D429B6287C68DD9
2 changed files with 29 additions and 0 deletions

View File

@ -20,4 +20,30 @@ public class EnumerableExtensionTests
[TestCase(new object[] { "hi", "there" }, false, "there", ExpectedResult = new object[] { "hi", "there" })]
public object[] TestConditionalWhere(object[] input, bool condition, object valueToKeep) =>
input.ConditionalWhere(condition, x => x.Equals(valueToKeep)).ToArray();
[Test]
public void TestConditionalAppendWithMaybe_HasAppendedItem_WhenMaybeHasValue()
{
var baseArray = new[] { 0, 1, 2 };
var result = baseArray
.ConditionalAppend(Maybe.Just(3))
.ToArray();
Assert.That(result, Has.Length.EqualTo(4));
Assert.That(result, Is.EquivalentTo(new[] { 0, 1, 2, 3 }));
}
[Test]
public void TestConditionalAppendWithMaybe_DoesNotHaveAppendedItem_WhenMaybeIsEmpty()
{
var baseArray = new[] { 0, 1, 2 };
var result = baseArray
.ConditionalAppend(Maybe.Empty<int>())
.ToArray();
Assert.That(result, Has.Length.EqualTo(3));
Assert.That(result, Is.EquivalentTo(new[] { 0, 1, 2 }));
}
}

View File

@ -11,6 +11,9 @@ public static class EnumerableExtensions
public static IEnumerable<T> ConditionalAppend<T>(this IEnumerable<T> enumerable, bool condition, T second) =>
condition ? enumerable.Append(second) : enumerable;
public static IEnumerable<T> ConditionalAppend<T>(this IEnumerable<T> enumerable, Maybe<T> item) =>
item.HasValue ? enumerable.Append(item.Value) : enumerable;
public static IEnumerable<T> ConditionalWhere<T>(this IEnumerable<T> enumerable, bool condition, Func<T, bool> pred) =>
!condition ? enumerable : enumerable.Where(pred);