A programming kata is an exercise which helps a programmer hone his skills through practice and repetition.
Tests that prove that the solution is correct are displayed below. Recommended way to solve this kata is to write the implementation for the first test, confirm that it passes and move to the next. Once all of the tests pass, the kata can be considered solved.
One possible solution is provided below the tests. Try to solve the kata by yourself first.
Develop an api that moves a rover around on a grid.
- You are given the initial starting point (x,y) of a rover and the direction (N,S,E,W) it is facing.
- The rover receives a character array of commands.
- Implement commands that move the rover forward/backward (f,b).
- Implement commands that turn the rover left/right (l,r).
- Implement wrapping from one edge of the grid to another. (planets are spheres after all)
- Implement obstacle detection before each move to a new square. If a given sequence of commands encounters an obstacle, the rover moves up to the last possible point and reports the obstacle.
Following is a set of unit tests that can be used to solve this kata in the TDD fashion.
One possible solution is following.
Full source is located in the GitHub repo https://github.com/vfarcic/mars-rover-kata-java-script. Besides tests and implementation, it includes package.json with NodeJS dependencies, Bower configuration with JS libraries and Grunt configuration that can be used run tests. README.md contains short instructions how to setup the project.
There are many ways to improve both tests and implementation of the provided solution. We could, for example:
- Check whether object values are correct. Location and grid must be number arrays consisting of two numbers.
- Check whether object values are correct. Direction must be one of following values: 'N', 'S', 'E', 'W'
- Check whether command values are correct Commands must be an arrays consisting of one of following values: 'f', 'b', 'l', 'r'.
- Change the code so that it works with both lower and upper cases (i.e 'N' or 'n' to specify north).
What was your solution? Post it as a comment so that we can compare different ways to solve this kata.