diff --git a/src/main/java/fi/solita/utils/functional/FunctionalImpl.java b/src/main/java/fi/solita/utils/functional/FunctionalImpl.java index 6f6546b..0892bf9 100644 --- a/src/main/java/fi/solita/utils/functional/FunctionalImpl.java +++ b/src/main/java/fi/solita/utils/functional/FunctionalImpl.java @@ -356,7 +356,7 @@ public static Pair> split(Iterable xs) { public static final Iterable every(int nth, Iterable xs) { // TODO: optimize... - return Functional.map(Transformers.right(), Functional.filter(Transformers._1().andThen(Predicates.divisible(nth)), Functional.zipWithIndex(xs))); + return nth < 0 ? Collections.emptyList() : nth == 0 ? headOption(xs) : Functional.map(Transformers.right(), Functional.filter(Transformers._1().andThen(Predicates.divisible(nth)), Functional.zipWithIndex(xs))); } static final boolean isEmpty(Iterable xs) { diff --git a/src/test/java/fi/solita/utils/functional/FunctionalTest.java b/src/test/java/fi/solita/utils/functional/FunctionalTest.java index d708369..5e64288 100644 --- a/src/test/java/fi/solita/utils/functional/FunctionalTest.java +++ b/src/test/java/fi/solita/utils/functional/FunctionalTest.java @@ -423,4 +423,14 @@ public void testIntersection() { assertEquals(newSet(2), Functional.intersection(newSet(1,2), newSet(2,3))); assertEquals(newSet(2), Functional.intersection(Arrays.asList(newSet(1,2), newSet(2,3)))); } + + @Test + public void testEvery() { + assertEquals(emptyList(), newList(Functional.every(-1, newList(0,1,2,3,4,5)))); + assertEquals(newList(0), newList(Functional.every(0, newList(0,1,2,3,4,5)))); + assertEquals(newList(0,1,2,3,4,5), newList(Functional.every(1, newList(0,1,2,3,4,5)))); + assertEquals(newList(0,2,4), newList(Functional.every(2, newList(0,1,2,3,4,5)))); + assertEquals(newList(0,3), newList(Functional.every(3, newList(0,1,2,3,4,5)))); + assertEquals(newList(0), newList(Functional.every(6, newList(0,1,2,3,4,5)))); + } }