Is there a way to simplify this code or at least m...
# getting-started
a
Is there a way to simplify this code or at least make it more beautiful ?
Copy code
val List<Int>.minmaxDifference get() = maxOf { it } - minOf { it }
// chestRoom is a set, blockX/Y/Z are Int
// CHEST_ROOM_MIN_SIZE & MAX_SIZE are const val Int

if (chestRoom.map { it.blockX }.minmaxDifference in CHEST_ROOM_MIN_SIZE..CHEST_ROOM_MAX_SIZE) return false
if (chestRoom.map { it.blockY }.minmaxDifference in CHEST_ROOM_MIN_SIZE..CHEST_ROOM_MAX_SIZE) return false
if (chestRoom.map { it.blockZ }.minmaxDifference in CHEST_ROOM_MIN_SIZE..CHEST_ROOM_MAX_SIZE) return false
e
I would probably write one of
Copy code
inline fun <T, R : Comparable<R>> Iterable<T>.minmaxOrNullBy(selector: (T) -> R): Pair<R, R>?
chestRoom.minmaxOrNullBy { it.blockX }?.let { (min, max) -> max - min in CHEST_ROOM_MIN_SIZE..CHEST_ROOM_MAX_SIZE }

inline fun <T> Iterable<T>.largestDeltaBy(selector: (T) -> Int): Int
chestRoom.largestDeltaBy { it.blockX } in CHEST_ROOM_MIN_SIZE..CHEST_ROOM_MAX_SIZE
instead
you could choose to be clever and write something like
Copy code
arrayOf(::blockX, ::blockY, ::blockZ)
    .any { largestDeltaBy(it) !in CHEST_ROOM_MIN_SIZE..CHEST_ROOM_MAX_SIZE }
but that doesn't really help clarity in this case, IMO
a
okay I see, it's a bit more clearer at least
b
I would consider switching from blockX/blockY/blockZ in the model to just an array, most likely you have similar repetitive code in other places In this case all the code will be simplified without a largestDeltaBy (if you still need I would suggest an
amplitudeOf { key }
name):
Copy code
return (0 until AXES).none { axe ->
    chest.maxOf { it.block[axe]} - chest.minOf { it.block[axe] } in  CHEST_ROOM_MIN_SIZE..CHEST_ROOM_MAX_SIZE
}
return (0 until AXES).