-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRover.js
79 lines (76 loc) · 2.08 KB
/
Rover.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class Rover {
constructor(upperX, upperY) {
this.upperX = upperX;
this.upperY = upperY;
this.N = 1;
this.E = 2;
this.S = 3;
this.W = 4;
this.x = 0;
this.y = 0;
this.facing = this.N;
}
//Change the rover position according to passed arguments
setPosition(x, y, dir) {
this.x = x;
this.y = y;
if (dir == 'N') {
this.facing = 1;
} else if (dir == 'E') {
this.facing = 2;
} else if (dir == 'S') {
this.facing = 3;
} else if (dir == 'W') {
this.facing = 4;
}
}
//Print the rover's position along with direction
printPosition() {
var direction;
if (this.facing == 1) {
direction = 'N';
} else if (this.facing == 2) {
direction = 'E';
} else if (this.facing == 3) {
direction = 'S';
} else if (this.facing == 4) {
direction = 'W'
}
return (this.x + " " + this.y + " " + direction)
}
turnLeft() {
this.facing = (this.facing - 1) < this.N ? this.W : this.facing - 1;
}
turnRight() {
this.facing = (this.facing + 1) > this.W ? this.N : this.facing + 1;
}
move() {
if (this.facing == this.N) {
this.y++;
} else if (this.facing == this.E) {
this.x++;
} else if (this.facing == this.S) {
this.y--;
} else if (this.facing == this.W) {
this.x--;
}
}
processRover(commands) {
for (var idx = 0; idx < commands.length; idx++) {
this.process1(commands.charAt(idx));
}
}
process1(command) {
if (command == 'L') {
this.turnLeft();
} else if (command == 'R') {
this.turnRight();
} else if (command == 'M') {
this.move();
} else {
console.log("Speak in Mars language, please!");
process.exit();
}
}
}
module.exports = Rover;