JavaScript Tutorial Through Katas: Mars Rover

A programming kata is an exercise which helps a programmer hone his skills through practice and repetition.

The article assumes that the reader is familiar with the basic usage of JavaScript and Jasmine asserts and knows how to run them from his favorite IDE (mine is WebStorm or IntelliJ IDEA).

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.

Mars Rover

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 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. 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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s