Created
December 4, 2020 02:24
-
-
Save GeePawHill/df31a66d34e757fdf15777e6c99d0426 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class SparseGrid<T>(val width: Int, val height: Int, val default: () -> T) { | |
| class IllegalCoordsException(coords: Coords) : RuntimeException("Illegal coordinates in SparseGrid $coords.") | |
| private val coordsToContents = mutableMapOf<Coords, T>() | |
| operator fun get(x: Int, y: Int): T = get(Coords(x, y)) | |
| operator fun get(coords: Coords) = coordsToContents.getOrDefault(validate(coords), default()) | |
| operator fun set(x: Int, y: Int, value: T) = set(Coords(x, y), value) | |
| operator fun set(coords: Coords, value: T) = coordsToContents.put(validate(coords), value) | |
| fun clear() = coordsToContents.clear() | |
| private fun validate(coords: Coords): Coords { | |
| if (coords.x < 0 || coords.y < 0 || coords.x >= width || coords.y >= height) throw IllegalCoordsException(coords) | |
| return coords | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment