Skip to content

Commit

Permalink
fix every for n <= 0
Browse files Browse the repository at this point in the history
  • Loading branch information
jyrimatti committed Dec 10, 2024
1 parent 7d3f49c commit 6d15a31
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ public static <T> Pair<T, Iterable<T>> split(Iterable<T> xs) {

public static final <T> Iterable<T> every(int nth, Iterable<T> xs) {
// TODO: optimize...
return Functional.map(Transformers.<T>right(), Functional.filter(Transformers.<Integer>_1().andThen(Predicates.divisible(nth)), Functional.zipWithIndex(xs)));
return nth < 0 ? Collections.<T>emptyList() : nth == 0 ? headOption(xs) : Functional.map(Transformers.<T>right(), Functional.filter(Transformers.<Integer>_1().andThen(Predicates.divisible(nth)), Functional.zipWithIndex(xs)));
}

static final boolean isEmpty(Iterable<?> xs) {
Expand Down
10 changes: 10 additions & 0 deletions src/test/java/fi/solita/utils/functional/FunctionalTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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))));
}
}

0 comments on commit 6d15a31

Please sign in to comment.