Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop up and down

Tags:

kotlin

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?

like image 962
Elye Avatar asked Aug 24 '26 00:08

Elye


2 Answers

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)
    }
}
like image 195
s1m0nw1 Avatar answered Aug 26 '26 09:08

s1m0nw1


This will do:

(0..13).forEach { colorized(colors, if (it > 6)  13 - it else it) }

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!