Skip to content

Commit

Permalink
Refactoring - made Field2D.atUnsafe private
Browse files Browse the repository at this point in the history
  • Loading branch information
jurisk committed Dec 3, 2023
1 parent 469ea87 commit a34fd99
Show file tree
Hide file tree
Showing 5 changed files with 11 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ object Advent13 {
}

def next(board: Field2D[Track]): Cart = {
val square = board.atUnsafe(coords)
val square = board.atOrElse(coords, Track.Empty)

val newDirection = square match {
case Track.Intersection =>
Expand All @@ -58,7 +58,7 @@ object Advent13 {
case Direction2D.W => N
case _ => sys.error(s"Unexpected direction $direction")
}
case _ => sys.error(s"Unexpected situation $square")
case Track.Empty => sys.error(s"Unexpected situation $square")
}

Cart(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ object Advent22 {
sanityCheck._1 shouldEqual position
sanityCheck._2.rotate(TurnAround) shouldEqual direction

field.atUnsafe(nextCoords) match {
field.atOrElse(nextCoords, Square.Outside) match {
case Square.Outside => sys.error("Should not happen")
case Square.Wall => this
case Square.Open =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ object Advent24 {

val withBlizzards = maze.blizzards.foldLeft(field) { case (acc, b) =>
val location = maze.blizzardAt(b, state.time)
val oldList = acc.atUnsafe(location)
val oldList = acc.atOrElse(location, Nil)
val newList = b.direction :: oldList
acc.updatedAtUnsafe(location, newList)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,10 @@ object Advent03 {
islands.map { island =>
val number = island.toList
.sortBy(_.x)
.map { c =>
field.atUnsafe(c).toChar
.flatMap { c =>
field.at(c)
}
.map(_.toChar)
.mkString
.toInt
(number, island)
Expand Down
5 changes: 4 additions & 1 deletion scala2/src/main/scala/jurisk/geometry/Field2D.scala
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,10 @@ final case class Field2D[T](
.lift(c.y - topLeft.y)
.flatMap(_.lift(c.x - topLeft.x))

def atUnsafe(c: Coords2D): T =
def atOrElse(c: Coords2D, default: => T): T =
at(c) getOrElse default

private def atUnsafe(c: Coords2D): T =
at(c) getOrElse sys.error(s"Coords2D $c are invalid")

def updatedAtUnsafe(c: Coords2D, newValue: T): Field2D[T] = {
Expand Down

0 comments on commit a34fd99

Please sign in to comment.