Skip to content

Commit

Permalink
re-use ForLoop elements without re-creating lists from scratch
Browse files Browse the repository at this point in the history
  • Loading branch information
slozenko committed Mar 15, 2024
1 parent bdbb829 commit a164bac
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/main/java/com/hubspot/jinjava/lib/filter/SliceFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,20 +80,26 @@ public Object filter(Object var, JinjavaInterpreter interpreter, String... args)
args[0]
);
}

List<List<Object>> result = new ArrayList<>();
List<Object> currentList = null; // lazy evaluation

List<Object> currentList = null;
int i = 0;
while (loop.hasNext()) {
Object next = loop.next();
if (i % slices == 0) {
currentList = new ArrayList<>(slices);
result.add(currentList);
if (currentList != null) {
result.add(currentList);
}
currentList = new ArrayList<>();
}
currentList.add(next);
currentList.add(loop.next());
i++;
}

if (currentList != null && !currentList.isEmpty()) {
result.add(currentList);
}

if (args.length > 1 && currentList != null) {
Object fillWith = args[1];
while (currentList.size() < slices) {
Expand Down

0 comments on commit a164bac

Please sign in to comment.