commonMain.ru.casperix.math.array.CustomMap2D.kt Maven / Gradle / Ivy
package ru.casperix.math.array
import ru.casperix.math.axis_aligned.int32.Dimension2i
import ru.casperix.math.vector.int32.Vector2i
import kotlinx.serialization.Serializable
@Serializable
data class CustomMap2D(override val dimension: Vector2i, val array: MutableList) : IndexedMap2D, MutableMap2D {
override fun setByIndex(index: Int, value: T) {
array[index] = value
}
override fun getByIndex(index: Int): T {
return array[index]
}
companion object {
fun create(dimension: Vector2i, builder: (index: Int) -> Custom): CustomMap2D {
val items = ArrayList(dimension.volume())
for (index in 0 until dimension.volume()) {
items.add(builder(index))
}
return CustomMap2D(dimension, items)
}
fun createByXY(dimension: Vector2i, builder: (position: Vector2i) -> Custom): CustomMap2D {
val items = ArrayList(dimension.volume())
for (y in 0 until dimension.y) {
for (x in 0 until dimension.x) {
val position = Vector2i(x, y)
items.add(builder(position))
}
}
return CustomMap2D(dimension, items)
}
}
init {
if (array.size != dimension.volume()) throw Error("Invalid array size. Need: ${dimension.volume()}")
}
fun map(convertor: (T) -> R): CustomMap2D {
return create(dimension) { index ->
val item = array[index]
convertor(item)
}
}
fun forEach(next: (Vector2i, T) -> Unit) {
array.forEachIndexed { index, value ->
val position = ArrayAccessND.position2D(dimension, index)
next(position, value)
}
}
}