Skip to content

Commit 9d24378

Browse files
committed
Take deforests
1 parent 47eccfe commit 9d24378

File tree

3 files changed

+45
-2
lines changed

3 files changed

+45
-2
lines changed

src/main/java/com/jnape/palatable/lambda/functions/builtin/fn2/Take.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import com.jnape.palatable.lambda.functions.Fn1;
44
import com.jnape.palatable.lambda.functions.Fn2;
5-
import com.jnape.palatable.lambda.iteration.TakingIterator;
5+
import com.jnape.palatable.lambda.iteration.TakingIterable;
66

77
/**
88
* Lazily limit the <code>Iterable</code> to <code>n</code> elements by returning an <code>Iterable</code> that stops
@@ -22,7 +22,7 @@ private Take() {
2222

2323
@Override
2424
public Iterable<A> apply(Integer n, Iterable<A> as) {
25-
return () -> new TakingIterator<>(n, as.iterator());
25+
return new TakingIterable<>(n, as);
2626
}
2727

2828
@SuppressWarnings("unchecked")
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.jnape.palatable.lambda.iteration;
2+
3+
import java.util.Iterator;
4+
5+
import static java.lang.Math.min;
6+
7+
public final class TakingIterable<A> implements Iterable<A> {
8+
private final int n;
9+
private final Iterable<A> as;
10+
11+
public TakingIterable(int n, Iterable<A> as) {
12+
while (as instanceof TakingIterable) {
13+
TakingIterable<A> nested = (TakingIterable<A>) as;
14+
n = min(n, nested.n);
15+
as = nested.as;
16+
}
17+
this.n = n;
18+
this.as = as;
19+
}
20+
21+
@Override
22+
public Iterator<A> iterator() {
23+
return new TakingIterator<>(n, as.iterator());
24+
}
25+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.jnape.palatable.lambda.iteration;
2+
3+
import com.jnape.palatable.lambda.functions.Fn1;
4+
import com.jnape.palatable.traitor.annotations.TestTraits;
5+
import com.jnape.palatable.traitor.runners.Traits;
6+
import org.junit.runner.RunWith;
7+
import testsupport.traits.Deforesting;
8+
9+
import static com.jnape.palatable.lambda.functions.builtin.fn2.Take.take;
10+
11+
@RunWith(Traits.class)
12+
public class TakingIterableTest {
13+
14+
@TestTraits({Deforesting.class})
15+
public Fn1<Iterable<Integer>, Iterable<Integer>> testSubject() {
16+
return take(1);
17+
}
18+
}

0 commit comments

Comments
 (0)