Created
November 20, 2020 07:36
-
-
Save AlexZhukovich/f8decf8acbe727a1d33da1dc34c9b494 to your computer and use it in GitHub Desktop.
Kotlin: Custom Range - Restaurant delivery time options
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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