Skip to content

Instantly share code, notes, and snippets.

@alf239
Last active May 31, 2016 21:59
Show Gist options
  • Select an option

  • Save alf239/eb1bb6655dd883dce0aecc4142a77f41 to your computer and use it in GitHub Desktop.

Select an option

Save alf239/eb1bb6655dd883dce0aecc4142a77f41 to your computer and use it in GitHub Desktop.
object Direction extends Enumeration {
type Direction = Value
val NORTH, EAST, SOUTH, WEST, NONE = Value
def getFromShortName(shortName: Char): Direction = shortName match {
case 'N' => NORTH
case 'E' => EAST
case 'S' => SOUTH
case 'W' => WEST
case _ => NONE
}
def turnLeft(d: Direction): Direction = d match {
case NORTH => WEST
case EAST => NORTH
case SOUTH => EAST
case WEST => SOUTH
case _ => NONE
}
def turnRight(d: Direction): Direction = d match {
case NORTH => EAST
case EAST => SOUTH
case SOUTH => WEST
case WEST => NORTH
case _ => NONE
}
implicit class DirectionOps(d: Direction) {
def turnLeft: Direction = Direction.turnLeft(d)
def turnRight: Direction = Direction.turnRight(d)
}
}
import org.specs2.mutable.Specification
class DirectionSpec extends Specification {
"Direction" should {
"whenGetFromShortNameWThenReturnDirectionW" in {
val direction = Direction.getFromShortName('W')
direction === Direction.WEST
}
"whenGetFromShortNameBThenReturnNone" in {
val direction = Direction.getFromShortName('B')
direction === Direction.NONE
}
"givenSWhenLeftThenE" in {
Direction.SOUTH.turnLeft === Direction.EAST
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment