Repository navigation
Expand file tree
/
Copy pathexample.js
More file actions
87 lines (72 loc) · 1.96 KB
/
Copy pathexample.js
File metadata and controls
87 lines (72 loc) · 1.96 KB
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
80
81
82
83
84
85
86
87
var Robot = (function () {
'use strict';
var VALID_DIRECTIONS = ['north', 'east', 'south', 'west'];
var INSTRUCTION_KEYS = {
A: 'advance',
L: 'turnLeft',
R: 'turnRight'
};
function Robot() {
this.coordinates = [0, 0];
this.bearing = 'north';
}
Robot.prototype.at = function (x, y) {
this.coordinates = [x, y];
};
Robot.prototype.orient = function (direction) {
if (VALID_DIRECTIONS.indexOf(direction) === -1) {
throw new Error('Invalid Robot Bearing');
}
this.bearing = direction;
};
Robot.prototype.advance = function () {
switch (this.bearing) {
case 'north':
this.coordinates[1]++;
break;
case 'east':
this.coordinates[0]++;
break;
case 'south':
this.coordinates[1]--;
break;
case 'west':
this.coordinates[0]--;
break;
}
};
Robot.prototype.turnLeft = function () {
var directionPosition = VALID_DIRECTIONS.indexOf(this.bearing);
if (directionPosition > 0) {
this.orient(VALID_DIRECTIONS[--directionPosition]);
} else {
this.orient(VALID_DIRECTIONS[VALID_DIRECTIONS.length - 1]);
}
};
Robot.prototype.turnRight = function () {
var directionPosition = VALID_DIRECTIONS.indexOf(this.bearing);
if (directionPosition < (VALID_DIRECTIONS.length - 1)) {
this.orient(VALID_DIRECTIONS[++directionPosition]);
} else {
this.orient(VALID_DIRECTIONS[0]);
}
};
Robot.prototype.instructions = function (instructionKeys) {
return instructionKeys.split('')
.map(function (key) {
return INSTRUCTION_KEYS[key];
});
};
Robot.prototype.place = function (args) {
this.coordinates = [args.x, args.y];
this.bearing = args.direction;
};
Robot.prototype.evaluate = function (instructionKeys) {
this.instructions(instructionKeys)
.forEach(function (instruction) {
this[instruction]();
}, this);
};
return Robot;
})();
module.exports = Robot;