Skip to content

Instantly share code, notes, and snippets.

@kiwiupover
Last active August 29, 2015 14:07
Show Gist options
  • Save kiwiupover/e04143c87a6c642c81f3 to your computer and use it in GitHub Desktop.
Save kiwiupover/e04143c87a6c642c81f3 to your computer and use it in GitHub Desktop.
Rover
// a answer to the rover interview question http://www.techinterviewpuzzles.com/2010/09/mars-rovers-thoughtworks-puzzles.html
describe("Rover", function() {
function rover(startCords, movement) {
var x = Number( startCords[0] );
var y = Number( startCords[2] );
var direction = startCords.charAt( startCords.length -1 );
var steps = movement.split('');
steps.forEach( function(step){
if ( step === 'L' || step === 'R' ) {
return direction = turn(direction, step);
}
return move(direction);
});
function move(dir){
switch (dir) {
case 'N':
y += 1
break;
case 'E':
x += 1
break;
case 'S':
y += -1
break;
case 'W':
x += -1
break;
}
}
return [x, y, direction].join(' ');
}
function turn(start, dir) {
var directions = ['N', 'E', 'S', 'W'];
var index = directions.indexOf(start);
if (dir === 'R') {
index = (index + 1 > 3) ? 0 : index + 1
return directions[index];
}
if (dir === 'L') {
index = (index - 1 < 0) ? 3 : index - 1
return directions[index];
}
}
describe("turn() truns around the weather compass", function(){
it("turns right", function(){
var expected = 'E';
expect( turn('N', 'R') ).to.eq(expected);
});
it("turns left", function(){
var expected = 'W';
expect( turn('N', 'L') ).to.eq(expected);
})
});
it("moves the rover by passing args", function(){
var expected = '1 3 N';
expect( rover('1 2 N', 'LMLMLMLMM') ).to.eq(expected);
});
it("moves the rover by passing args", function(){
var expected = '5 1 E';
expect( rover('3 3 E', 'MMRMMRMRRM') ).to.eq(expected);
});
});
@brirob1113
Copy link

I like how you calculated the turn, using an array and quick indexing hopping.

If this was ruby I would want the code to be cleaned/tightened up a bit more.

Lin 14 and 17, I like how move and turn are two different functions. One suggestion would be that I think it's a bit odd that move will change the variable for you and turn returns a value that you then set. It would be less confusing if they matched in that regards.

Not sure why you did: '
var direction = startCords.charAt( startCords.length -1 );
instead of:
var direction = startCords.charAt( 4 );
to match how you were grabbing chars before.

Overall, it looks pretty good. As mentioned above, I would tighten the code up if it were in ruby but not sure about js. Also, a part of this exercise is working through it with the person but the code side of it looks good.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment