Hello, anyone can create an Iterator to iterate ov...
# android
s
Hello, anyone can create an Iterator to iterate over java.LocalTime without creating an infinite loop? I have this but this is looping forever... 😄
Copy code
class TimeIterator(
    startTime: LocalTime,
    private val endTimeInclusive: LocalTime,
    private val stepMinutes: Long,
) : Iterator<LocalTime> {

    private var currentTime = startTime

    override fun hasNext(): Boolean {
        return currentTime <= endTimeInclusive
    }

    override fun next(): LocalTime {
        val next = currentTime
        currentTime = currentTime.plusMinutes(stepMinutes)
        return next
    }
}
z
This looks okay, for what inputs does it loop forever, and what values is it producing as it loops?
I don’t see why this would loop outside of
stepMinutes = 0
s
try it with endTime = "00:00"
LocalTime.parse("00:00")
or startTime == "00:00" it does not iterate
doesn't look pretty now 😕
Copy code
class TimeIterator(
    private var startTime: LocalTime,
    private val endTimeInclusive: LocalTime,
    private val stepMinutes: Long,
) : Iterator<LocalTime> {

    private val zero = LocalTime.parse("00:00")
    private var currentTime = startTime
    private var stopNext = false
    private var stopFirst = true

    override fun hasNext(): Boolean {
        return currentTime <= endTimeInclusive && stopNext.not()
    }

    override fun next(): LocalTime {
        val next = currentTime
        currentTime = currentTime.plusMinutes(stepMinutes)
        if (next == zero) {
            stopNext = true
            if (startTime == zero && stopFirst) {
                stopNext = false
                stopFirst = false
            }
        }
        return next
    }
}
e
you need to be smarter about checking for overflow,
Copy code
LocalTime.of(23, 58).plusMinutes(5) == LocalTime.of(0, 3)
will never reach 00:00
s
in that case yes
in my usecase I'll allways have 15 minute intervals from the exact hour
e
even if that's the case, it's easy to handle correctly
Copy code
fun timeIterator(startTime: LocalTime, endTimeInclusive: LocalTime, stepMinutes: Long): Sequence<LocalTime> =
    generateSequence(startTime) { prev ->
        val next = prev.plusMinutes(stepMinutes)
        if (next > prev && next <= endInclusive) next else null
    }
👍 1
s
nice. will try to use this. Also looked at generateSequence but couldn't figure it out