I have the below code
(0..6).forEach { colorized(colors, it) }
(6 downTo 0).forEach { colorized(colors, it) }
Where I loop up and down. Is there a way to achieve it in one loop instead of two?
A simple extension on IntRange can solve it:
fun IntRange.forEachUpAndDown(action: (Int) -> Unit) {
forEach(action)
reversed().forEach(action)
}
fun main(args: Array<String>) {
(0..6).forEachUpAndDown {
println(it)
}
}
This will do:
(0..13).forEach { colorized(colors, if (it > 6) 13 - it else it) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With