diff --git a/src/main/java/net/andreinc/mockneat/abstraction/MockUnit.java b/src/main/java/net/andreinc/mockneat/abstraction/MockUnit.java index 37f6d67..6211b55 100644 --- a/src/main/java/net/andreinc/mockneat/abstraction/MockUnit.java +++ b/src/main/java/net/andreinc/mockneat/abstraction/MockUnit.java @@ -179,6 +179,46 @@ default MockUnit map(Function function) { return () -> supp; } + /** + *

Returns a generator consisting of the elements of this generator that match the given predicate.

+ * + * @param predicate The {@code Predicate} applied to the generated value in the intermediary step to determine if it should be returned. + * @return A new MockUnit + */ + default MockUnit filter(Predicate predicate) { + notNull(predicate, "predicate"); + Supplier supp = () -> { + T val = val(); + while (!predicate.test(val)) { + val = val(); + } + return val; + }; + return () -> supp; + } + + /** + *

Returns a generator consisting of the distinct elements (according to {@link Object#equals(Object)}) of this generator.

+ * + * @param function The {@code Function} applied to the generated value for check for unique. + * @param The type of the values for check for unique. + * @return A new MockUnit + */ + default MockUnit distinctBy(Function function) { + notNull(function, "function"); + Set seen = new HashSet<>(); + return filter(it -> seen.add(function.apply(it))); + } + + /** + *

Returns a generator consisting of the distinct elements (according to {@link Object#equals(Object)}) of this generator.

+ * + * @return A new MockUnit + */ + default MockUnit distinct() { + return distinctBy(Function.identity()); + } + /** *

This method is used to transform a {@code MockUnit} into a {@code MockUnitInt}.

* diff --git a/src/test/java/net/andreinc/mockneat/abstraction/MockUnitFilterMethodTest.java b/src/test/java/net/andreinc/mockneat/abstraction/MockUnitFilterMethodTest.java new file mode 100644 index 0000000..1311d2d --- /dev/null +++ b/src/test/java/net/andreinc/mockneat/abstraction/MockUnitFilterMethodTest.java @@ -0,0 +1,39 @@ +package net.andreinc.mockneat.abstraction; + +import org.junit.Test; + +import static net.andreinc.mockneat.Constants.*; +import static net.andreinc.mockneat.utils.LoopsUtils.loop; +import static org.junit.Assert.assertEquals; + +public class MockUnitFilterMethodTest { + + @Test(expected = NullPointerException.class) + public void testFilterNullFunc() { + M.ints().filter(null); + } + + @Test(expected = NullPointerException.class) + public void testDistinctByNullFunc() { + M.ints().distinctBy(null); + } + + @Test + public void testFilterEven() { + loop(MOCK_CYCLES, + MOCKS, + m -> m.ints().filter(it -> it % 2 == 0).val(), + v -> assertEquals(0, v % 2) + ); + } + + @Test + public void testDistinct() { + loop(MOCK_CYCLES, + MOCKS, + m -> m.ints().rangeClosed(1, 10).distinct().set(10).val(), + v -> assertEquals(10, v.size()) + ); + } + +}