| 11 | 11 | } |
| 12 | 12 | |
| 13 | 13 | export class Robot { |
| 14 | constructor() { |
| 15 | this._bearing = 'north'; |
| 16 | this._coordinates = [0, 0]; |
| 17 | } |
| 18 | |
| 14 | 19 | get bearing() { |
| 15 | | throw new Error('Remove this line and implement the function'); |
| 20 | return this._bearing; |
| 16 | 21 | } |
| 17 | 22 | |
| 18 | 23 | get coordinates() { |
| 19 | | throw new Error('Remove this line and implement the function'); |
| 24 | return this._coordinates; |
| 20 | 25 | } |
| 21 | 26 | |
| 22 | 27 | place({ x, y, direction }) { |
| 23 | | throw new Error('Remove this line and implement the function'); |
| 28 | // Edge Case: Invalid direction |
| 29 | if (!['north', 'south', 'east', 'west'].includes(direction)) { |
| 30 | throw new InvalidInputError('Invalid Robot Bearing'); |
| 31 | } |
| 32 | |
| 33 | // Edge Case: Non-integer coordinates |
| 34 | if (!Number.isInteger(x) || !Number.isInteger(y)) { |
| 35 | throw new InvalidInputError('Invalid coordinates'); |
| 36 | } |
| 37 | |
| 38 | this._bearing = direction; |
| 39 | this._coordinates = [x, y]; |
| 24 | 40 | } |
| 25 | 41 | |
| 26 | 42 | evaluate(instructions) { |
| 27 | | throw new Error('Remove this line and implement the function'); |
| 43 | // Edge Case: Empty instruction string |
| 44 | if (instructions.length === 0) { |
| 45 | return; |
| 46 | } |
| 47 | |
| 48 | // Edge Case: Invalid instruction characters |
| 49 | for (const char of instructions) { |
| 50 | if (!['R', 'L', 'A'].includes(char)) { |
| 51 | throw new InvalidInputError('Invalid instruction'); |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | for (const instruction of instructions) { |
| 56 | switch (instruction) { |
| 57 | case 'R': |
| 58 | this._turnRight(); |
| 59 | break; |
| 60 | case 'L': |
| 61 | this._turnLeft(); |
| 62 | break; |
| 63 | case 'A': |
| 64 | this._advance(); |
| 65 | break; |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | _turnRight() { |
| 71 | const directions = ['north', 'east', 'south', 'west']; |
| 72 | const currentIndex = directions.indexOf(this._bearing); |
| 73 | this._bearing = directions[(currentIndex + 1) % 4]; |
| 74 | } |
| 75 | |
| 76 | _turnLeft() { |
| 77 | const directions = ['north', 'west', 'south', 'east']; |
| 78 | const currentIndex = directions.indexOf(this._bearing); |
| 79 | this._bearing = directions[(currentIndex + 1) % 4]; |
| 80 | } |
| 81 | |
| 82 | _advance() { |
| 83 | const [x, y] = this._coordinates; |
| 84 | |
| 85 | switch (this._bearing) { |
| 86 | case 'north': |
| 87 | this._coordinates = [x, y + 1]; |
| 88 | break; |
| 89 | case 'south': |
| 90 | this._coordinates = [x, y - 1]; |
| 91 | break; |
| 92 | case 'east': |
| 93 | this._coordinates = [x + 1, y]; |
| 94 | break; |
| 95 | case 'west': |
| 96 | this._coordinates = [x - 1, y]; |
| 97 | break; |
| 98 | } |
| 28 | 99 | } |
| 29 | 100 | } |
| 101 | |
| 102 | // Handled Edge Cases: Invalid direction, Non-integer coordinates, Empty instruction string, Invalid instruction characters |