Skip to content

Commit

Permalink
optimized function usage
Browse files Browse the repository at this point in the history
  • Loading branch information
rainett committed Aug 3, 2024
1 parent 5ab67f7 commit 7ebd679
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 14 deletions.
13 changes: 7 additions & 6 deletions src/main/java/core/basesyntax/Robot.java
Original file line number Diff line number Diff line change
Expand Up @@ -92,21 +92,22 @@ public void faceDown() {

public void faceRight() {
faceLeft();
turnLeft();
turnLeft();
turnAround();
}

public void faceLeft() {
switch (getDirection()) {
case UP -> turnLeft();
case RIGHT -> {
turnLeft();
turnLeft();
}
case RIGHT -> turnAround();
case DOWN -> turnRight();
default -> {

}
}
}

public void turnAround() {
turnLeft();
turnLeft();
}
}
14 changes: 6 additions & 8 deletions src/main/java/core/basesyntax/RobotRoute.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,19 @@

public class RobotRoute {
public void moveRobot(Robot robot, int toX, int toY) {
alignCoordinate(Robot::getX, robot, Robot::faceLeft, Robot::faceRight, toX);
alignCoordinate(Robot::getY, robot, Robot::faceDown, Robot::faceUp, toY);
alignCoordinate(Robot::getX, Robot::faceLeft, robot, toX);
alignCoordinate(Robot::getY, Robot::faceDown, robot, toY);
}

private void alignCoordinate(Function<Robot, Integer> robotCoordinateFunction,
Robot robot,
Consumer<Robot> faceNegativeConsumer,
Consumer<Robot> facePositiveConsumer,
Robot robot,
int coordinate) {
int robotCoordinate = robotCoordinateFunction.apply(robot);
while (robotCoordinate != coordinate) {
if (robotCoordinate > coordinate) {
faceNegativeConsumer.accept(robot);
} else {
facePositiveConsumer.accept(robot);
faceNegativeConsumer.accept(robot);
if (robotCoordinate < coordinate) {
robot.turnAround();
}
robot.stepForward();
robotCoordinate = robotCoordinateFunction.apply(robot);
Expand Down

0 comments on commit 7ebd679

Please sign in to comment.