Skip to content

Commit

Permalink
Added extension JustWhen to Maybe<T> (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
apfohl authored May 2, 2021
1 parent 7a9479f commit 3472ef1
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
10 changes: 9 additions & 1 deletion MonadicBits/MaybeExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Linq;

namespace MonadicBits
Expand All @@ -12,5 +13,12 @@ public static Maybe<T> JustNotNull<T>(this T value) =>

public static Maybe<T> FirstOrNothing<T>(this IEnumerable<T> source) =>
source.Select(value => value.Just()).DefaultIfEmpty(Maybe<T>.Nothing()).First();

public static Maybe<T> JustWhen<T>(this T value, Func<T, bool> predicate)
{
if (predicate == null) throw new ArgumentNullException(nameof(predicate));

return predicate(value) ? Maybe<T>.Just(value) : Maybe<T>.Nothing();
}
}
}
21 changes: 20 additions & 1 deletion MonadicBitsTests/MaybeExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using MonadicBits;
using NUnit.Framework;

Expand Down Expand Up @@ -34,5 +35,23 @@ public static void FirstOrNothing_with_list_of_values_returns_maybe_of_first_val
[Test]
public static void FirstOrNothing_with_empty_list_returns_nothing() =>
new List<int>().FirstOrNothing().Match(_ => Assert.Fail(), Assert.Pass);

[Test]
public static void JustWhen_with_null_predicate_throws_exception() =>
Assert.Throws<ArgumentNullException>(() => "Test".JustWhen(null));

[Test]
public static void JustWhen_with_false_predicate_returns_nothing()
{
const string input = "Test";
input.JustWhen(s => s.Length == input.Length + 1).Match(_ => Assert.Fail(), Assert.Pass);
}

[Test]
public static void JustWhen_with_true_predicate_returns_just()
{
const string input = "Test";
input.JustWhen(s => s.Length == input.Length).Match(_ => Assert.Pass(), Assert.Fail);
}
}
}

0 comments on commit 3472ef1

Please sign in to comment.