Skip to content

Commit e4d232a

Browse files
committed
extend grid methods
1 parent e313f9e commit e4d232a

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/main/kotlin/tr/emreone/kotlin_utils/extensions/Grid.kt

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@ val Grid<*>.width: Int get() = firstOrNull()?.size ?: 0
2121
val Grid<*>.height: Int get() = size
2222
val Grid<*>.area: Area get() = origin to lastPoint
2323

24+
val Iterable<Point>.area: Area get() = areaOrNull ?: error("No points given")
25+
val Iterable<Point>.areaOrNull: Area? get() = boundingArea()
26+
val MapGrid<*>.area: Area get() = areaOrNull ?: error("No points given in Map")
27+
val MapGrid<*>.areaOrNull: Area? get() = keys.boundingArea()
28+
29+
2430
/**
2531
* The last (bottom right) point in this [Grid] or `-1 to -1` for an empty Grid.
2632
*/
@@ -165,6 +171,23 @@ fun <T> MapGrid<T>.formatted(
165171
}
166172
}
167173

174+
fun <T> MapGrid<T>.formatted(
175+
area: Area? = null,
176+
filler: Any = ' ',
177+
reverseX: Boolean = false,
178+
reverseY: Boolean = false,
179+
showHeaders: Boolean = true,
180+
transform: (Point, T?) -> String? = { _, value -> "$value" },
181+
): String {
182+
val relevantArea = area ?: keys.boundingArea() ?: return "empty map, nothing to show"
183+
val default = filler.toString()
184+
return relevantArea.buildFormatted(reverseX, reverseY, showHeaders) { col, row ->
185+
val point = col to row
186+
val value = get(point)
187+
transform(col to row, value) ?: default
188+
}
189+
}
190+
168191
fun Iterable<Point>.plot(
169192
restrictArea: Area? = null, on: String = "#", off: String = " ",
170193
reverseX: Boolean = false,

src/main/kotlin/tr/emreone/kotlin_utils/math/PointsAndAreas.kt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,17 @@ inline fun Area.forBorder(f: (p: Point) -> Unit) {
165165
}
166166

167167
operator fun Area.contains(p: Point) = p.x in first.x..second.x && p.y in first.y..second.y
168+
operator fun Area.plus(amount: Int) = grow(by = amount)
169+
operator fun Area.minus(amount: Int) = shrink(by = amount)
170+
171+
const val LEFT_ARROW = '\u2190'
172+
const val UP_ARROW = '\u2191'
173+
const val RIGHT_ARROW = '\u2192'
174+
const val DOWN_ARROW = '\u2193'
175+
const val NW_ARROW = '\u2196'
176+
const val NE_ARROW = '\u2197'
177+
const val SE_ARROW = '\u2198'
178+
const val SW_ARROW = '\u2199'
168179

169180
val Area.width: Int
170181
get() = (second.x - first.x + 1).coerceAtLeast(0)

0 commit comments

Comments
 (0)