Skip to content

Instantly share code, notes, and snippets.

@jcraane
Created March 6, 2022 19:42
Show Gist options
  • Save jcraane/2a4652e3daaae76807e8bc6e730d6e0d to your computer and use it in GitHub Desktop.
Save jcraane/2a4652e3daaae76807e8bc6e730d6e0d to your computer and use it in GitHub Desktop.
Complement for Distance.kt
import kotlin.math.abs
import kotlin.math.roundToLong
enum class DistanceUnit(private val orderLowerIsLarger: Int) {
KILOMETERS(1),
HECTOMETERS(2),
DECAMETERS(3),
METERS(4),
DECIMETERS(5),
CENTIMETERS(6),
MILLIMETERS(7);
fun convert(value: Double, other: DistanceUnit): Long {
val firstIndex = largestFirst.indexOf(this)
val lastIndex = largestFirst.indexOf(other)
val (numberOfZeros, inversion) = if (firstIndex > lastIndex) {
firstIndex - lastIndex to -1
} else {
lastIndex - firstIndex to 1
}
val factor = (0 until numberOfZeros).fold("1") { acc, _ ->
acc + "0"
}.toLong() * inversion
return (if (factor < 0) {
abs(value / factor)
} else {
value * factor
}.roundToLong()
) }
companion object {
val largestFirst = values().sortedBy { it.orderLowerIsLarger }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment