Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Kotlin: Custom Range - Restaurant delivery time options
data class Restaurant(
val id: Long,
val name: String,
val openTime: Date,
val closeTime: Date
) {
private val deliveryTimeStep: Long = 15 * 60 * 1000
fun getDeliveryTimeOptions(): DeliveryTimeOptions {
return openTime..closeTime step deliveryTimeStep
}
}
class DeliveryTimeOptions(
override val start: Date,
override val endInclusive: Date,
private val stepTime: Long = 3_600_000
) : ClosedRange<Date>, Iterable<Date> {
override fun iterator(): Iterator<Date> {
return DeliveryTimeIterator(start, endInclusive, stepTime)
}
infix fun step(stepTime: Long) = DeliveryTimeOptions(start, endInclusive, stepTime)
}
class DeliveryTimeIterator(
private val start: Date,
private val endInclusive: Date,
private val stepTime: Long
): Iterator<Date> {
private var currentValue = start.time
override fun hasNext(): Boolean {
return currentValue <= endInclusive.time
}
override fun next(): Date {
val next = currentValue
currentValue += stepTime
return Date(next)
}
}
operator fun Date.rangeTo(other: Date) = DeliveryTimeOptions(this, other)
fun main() {
val openTime = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 9)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
}
val closeTime = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 17)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
}
val restaurant = Restaurant(
id = 42L,
name = "FooBar",
openTime = openTime.time,
closeTime = closeTime.time
)
restaurant.getDeliveryTimeOptions().toList()
.forEach { println(it) }
}
@AlexZhukovich

This comment has been minimized.

Copy link
Owner Author

@AlexZhukovich AlexZhukovich commented Nov 20, 2020

Output:
Fri Nov 20 09:00:00 CET 2020
Fri Nov 20 09:15:00 CET 2020
Fri Nov 20 09:30:00 CET 2020
...
Fri Nov 20 16:30:00 CET 2020
Fri Nov 20 16:45:00 CET 2020
Fri Nov 20 17:00:00 CET 2020

@AlexZhukovich

This comment has been minimized.

Copy link
Owner Author

@AlexZhukovich AlexZhukovich commented Nov 20, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.