Skip to content

Commit

Permalink
#236: Keep track of the last iterable instead of the last iteration a…
Browse files Browse the repository at this point in the history
…nd count the iterations of the iterable afterwards.
  • Loading branch information
mvanaken committed Jul 20, 2018
1 parent 0d2401b commit ad98634
Showing 1 changed file with 9 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,20 +46,21 @@ public class CurrentIteration implements ValueExpression {

@Override
public ImmutableList<Optional<Value>> eval(final ParseState parseState, final Encoding encoding) {
final BigInteger currentIndex = findCurrentIteration(parseState.order, ZERO).computeResult();
return ImmutableList.create(Optional.of(createFromNumeric(currentIndex, new Encoding())));
final ParseGraph iterable = findIterable(parseState.order, ParseGraph.EMPTY).computeResult();
final BigInteger iteration = countIterable(iterable, ZERO).computeResult().max(ZERO);
return ImmutableList.create(Optional.of(createFromNumeric(iteration, new Encoding())));
}

private Trampoline<BigInteger> findCurrentIteration(final ParseItem item, final BigInteger currentIndex) {
if (!item.isGraph()) { return complete(() -> currentIndex); }
private Trampoline<ParseGraph> findIterable(final ParseItem item, final ParseGraph iterableCandidate) {
if (!item.isGraph()) { return complete(() -> iterableCandidate); }
if (item.getDefinition().isIterable()) {
return intermediate(() -> findCurrentIteration(item.asGraph().head, countIterables(item.asGraph(), ZERO).computeResult()));
return intermediate(() -> findIterable(item.asGraph().head, item.asGraph()));
}
return intermediate(() -> findCurrentIteration(item.asGraph().head, currentIndex));
return intermediate(() -> findIterable(item.asGraph().head, iterableCandidate));
}

private Trampoline<BigInteger> countIterables(final ParseGraph graph, final BigInteger count) {
if (!graph.isEmpty()) { return intermediate(() -> countIterables(graph.tail, count.add(ONE))); }
private Trampoline<BigInteger> countIterable(final ParseGraph graph, final BigInteger count) {
if (!graph.isEmpty()) { return intermediate(() -> countIterable(graph.tail, count.add(ONE))); }
return complete(() -> count.subtract(ONE));
}

Expand Down

0 comments on commit ad98634

Please sign in to comment.