Created
January 10, 2017 09:56
-
-
Save pfcoperez/cb9db213d896e15af19b560929174e63 to your computer and use it in GitHub Desktop.
This file contains 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
object SimulationCLI extends App { | |
type CommandAction = (Seq[String], ElevatorControlSystemAPI) => Option[ElevatorControlSystemAPI] | |
val commands: Map[String, CommandAction] = | |
Map( | |
"state" -> { (args, ecs) => | |
ecs.status.toSeq.sortBy(_._1) foreach { | |
case (elevatorId, ElevatorState(movement, floor)) => | |
val movementStr = movement map { | |
case Up => "/\\" | |
case Down => "\\/" | |
} getOrElse "--" | |
println(s"$floor $movementStr <- $elevatorId") | |
} | |
Some(ecs) | |
}, | |
"quit" -> { (_, _) => None }, | |
"step" -> { (_, ecs) => | |
println("Executed one simulation step") | |
Some(ecs.step) | |
}, | |
"pickup" -> { (args, ecs) => | |
if(args.size != 2 || | |
args(0).exists(c => !('0' to '9').contains(c) && c != '-') || | |
!Set("up", "down").contains(args(1).trim.toLowerCase) | |
) { | |
println(s"Invalid pickup request: $args") | |
} else { | |
val floor = args(0).toInt | |
val direction = if(args(1) == "up") Up else Down | |
val pickupPromise = ecs.passengerCommand(PickUp(floor, direction)) | |
pickupPromise.onSuccess { case rq => println("Completed task: " + rq) } { | |
scala.concurrent.ExecutionContext.Implicits.global | |
} | |
println(s"Registered pick up request to $floor $direction") | |
} | |
Some(ecs) | |
} | |
) | |
val invalidCommand: CommandAction = { | |
(_, ecs) => | |
println("INVALID COMMAND") | |
Some(ecs) | |
} | |
def repl(currentSystem: ElevatorControlSystemAPI): Unit = { | |
print("> ") | |
val Array(command, arguments @ _*) = readLine.split(' ').map(_.trim) | |
val newSystem = commands.getOrElse(command, invalidCommand)(arguments, currentSystem) | |
//Not using map in order to make a tail recursive call | |
if(newSystem.isDefined) repl(newSystem.get) | |
} | |
repl(ElevatorControlSystem()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment