Skip to content

Commit

Permalink
Replace interator with Stream interation over localdates
Browse files Browse the repository at this point in the history
  • Loading branch information
derTobsch committed Jan 3, 2025
1 parent 00427a2 commit 35b50d5
Showing 1 changed file with 5 additions and 40 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,12 @@
import de.focus_shift.jollyday.core.spi.FixedWeekdayBetweenFixed;

import java.time.LocalDate;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Function;
import java.util.stream.StreamSupport;
import java.util.stream.Stream;

import static java.util.Spliterator.IMMUTABLE;
import static java.util.Spliterator.ORDERED;
import static java.util.Spliterators.spliteratorUnknownSize;
import static java.time.temporal.ChronoUnit.DAYS;

public class FindWeekDayBetween implements Function<FixedWeekdayBetweenFixed, LocalDate>, Iterable<LocalDate> {
public class FindWeekDayBetween implements Function<FixedWeekdayBetweenFixed, LocalDate> {

private final LocalDate from;
private final LocalDate to;
Expand All @@ -24,40 +20,9 @@ public FindWeekDayBetween(final LocalDate from, final LocalDate to) {

@Override
public LocalDate apply(final FixedWeekdayBetweenFixed fwm) {
return StreamSupport.stream(spliteratorUnknownSize(iterator(), ORDERED | IMMUTABLE), false)
return Stream.iterate(from, date -> date.plusDays(1))
.limit(DAYS.between(from, to) + 1)
.filter(date -> date.getDayOfWeek() == fwm.weekday())
.findFirst().orElse(null);
}

@Override
public Iterator<LocalDate> iterator() {
return new FindWeekDayBetweenIterator(from, to);
}

private static final class FindWeekDayBetweenIterator implements Iterator<LocalDate> {

private LocalDate cursor;
private final LocalDate endDate;

FindWeekDayBetweenIterator(final LocalDate startDate, final LocalDate endDate) {
this.cursor = startDate;
this.endDate = endDate;
}

@Override
public boolean hasNext() {
return cursor.isBefore(endDate) || cursor.isEqual(endDate);
}

@Override
public LocalDate next() {
if (!hasNext()) {
throw new NoSuchElementException("next date is after endDate which is not in range anymore.");
}

final LocalDate current = cursor;
cursor = cursor.plusDays(1);
return current;
}
}
}

0 comments on commit 35b50d5

Please sign in to comment.