class WaypointShip {
constructor() {
this.north = 0;
this.east = 0;
this.waypointNorth = 1;
this.waypointEast = 10;
}
moveWaypoint(direction, amount) {
switch (direction) {
case 'N':
this.waypointNorth += amount;
break;
case 'S':
this.waypointNorth -= amount;
break;
case 'E':
this.waypointEast += amount;
break;
case 'W':
this.waypointEast -= amount;
break;
default:
throw `Bad direction: ${direction} : ${amount}`;
}
}
rotate(direction, amount) {
for (let i = 0; i < amount; i += 90) {
let newEast = this.waypointNorth,
newNorth = this.waypointEast;
if ('R' === direction) {
newNorth *= -1;
} else {
newEast *= -1;
}
this.waypointNorth = newNorth;
this.waypointEast = newEast;
}
return this;
}
execute(command) {
const action = command[0],
amount = parseInt(command.substring(1));
switch (action) {
case 'F':
this.north += this.waypointNorth * amount;
this.east += this.waypointEast * amount;
break;
case 'N':
case 'S':
case 'E':
case 'W':
this.moveWaypoint(action, amount);
break;
case 'R':
case 'L':
this.rotate(action, amount);
break;
default:
throw `Bad action: ${action} : ${amount}`;
}
return [action, amount];
}
}