Skip to content

Commit 48fa4ab

Browse files
authored
Merge pull request #45 from messerli-informatik-ag/option-where
Add Option.Where
2 parents 30db896 + b59b90f commit 48fa4ab

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

Funcky.Test/OptionTest.cs

+26
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,32 @@ public static IEnumerable<object[]> TestValues()
199199
yield return new object[] { "None", Option<MyEnum>.None() };
200200
}
201201

202+
[Theory]
203+
[MemberData(nameof(WhereTestValues))]
204+
public void WhereFiltersOptionCorrectly(Option<string> expectedResult, Option<string> input, Func<string, bool> predicate)
205+
{
206+
Assert.Equal(expectedResult, input.Where(predicate));
207+
}
208+
209+
[Theory]
210+
[MemberData(nameof(WhereTestValues))]
211+
public void OptionSupportsLinqWhereSyntax(Option<string> expectedResult, Option<string> input, Func<string, bool> predicate)
212+
{
213+
var result = from x in input
214+
where predicate(x)
215+
select x;
216+
Assert.Equal(expectedResult, result);
217+
}
218+
219+
public static TheoryData<Option<string>, Option<string>, Func<string, bool>> WhereTestValues()
220+
=> new TheoryData<Option<string>, Option<string>, Func<string, bool>>
221+
{
222+
{ Option.Some("foo"), Option.Some("foo"), True },
223+
{ Option<string>.None(), Option.Some("foo"), False },
224+
{ Option<string>.None(), Option<string>.None(), True },
225+
{ Option<string>.None(), Option<string>.None(), False },
226+
};
227+
202228
[Theory]
203229
[MemberData(nameof(TestValues))]
204230

Funcky/Monads/Option.cs

+3
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,9 @@ public Option<TResult> SelectMany<TMaybe, TResult>(Func<TItem, Option<TMaybe>> m
5050
return Option<TResult>.None();
5151
}
5252

53+
public Option<TItem> Where(Func<TItem, bool> predicate)
54+
=> AndThen(item => predicate(item) ? Option.Some(item) : None());
55+
5356
public TResult Match<TResult>(TResult none, Func<TItem, TResult> some)
5457
=> _hasItem
5558
? some(_item)

changelog.md

+1
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,4 @@
1515

1616
## Unreleased
1717
* Added overload for AndThen which flattens the Option
18+
* Add `Where` method to `Option<T>`, which allows filtering the `Option` by a predicate.

0 commit comments

Comments
 (0)