marble log

Webエンジニアの技術ブログです

【Kotlin】LocalDateにrangeToを実装

import java.time.LocalDate

internal class LocalDateProgression(
    override val start: LocalDate,
    override val endInclusive: LocalDate,
    private val stepDays: Long = 1
) :
    Iterable<LocalDate>, ClosedRange<LocalDate> {

    override fun iterator(): Iterator<LocalDate> = LocalDateIterator(start, endInclusive, stepDays)

    infix fun step(days: Long) = LocalDateProgression(start, endInclusive, days)

    internal class LocalDateIterator(
        startDate: LocalDate,
        private val endDateInclusive: LocalDate,
        private val stepDays: Long
    ) :
        Iterator<LocalDate> {

        private var currentDate = startDate

        override fun hasNext() = currentDate <= endDateInclusive

        override fun next(): LocalDate {
            val next = currentDate
            currentDate = currentDate.plusDays(stepDays)
            return next
        }
    }
}