I've recently started learning programing with JavaScript, so I figured that practice on CodeWars will be good place to learn. I'm stack on this particular kata for days, can somebody please tell me what is wrong with my code.
The tests should return false if the walk is too short, too long, and doesn't bring you back to start, and return true for valid walk. So far, my code returns false if the walk is too short or too long, and returns true if the walk is valid, but fails the test for bringing you back to start and the return I get is 'Value is not what was expected'.
function isValidWalk(walk) {
if (walk.length === 10) {return true}
else {return false};
let north = 0;
let south = 0;
let east = 0;
let west = 0;
for (i=0; i<walk.length; i++) {
if (walk[i] = 'n') {return north++}
else if (walk[i] == 's') {return south++}
else if (walk[i] == 'e') {return east++}
else if (walk[i] == 'w') {return west++}
};
if ((north == south) && (west == east)) {return true}
else {return false}
};
You're always returning in either the first or second line of the function. Remove the return true; part there, and your code should work.
You also have return's each time you're incrementing a direction, so remove that too.
There was also an accidental single = for walk[i] == 'n'.
function isValidWalk(walk) {
if (walk.length !== 10) return false;
let north = 0;
let south = 0;
let east = 0;
let west = 0;
for (i=0; i<walk.length; i++) {
if (walk[i] == 'n') north++;
else if (walk[i] == 's') south++;
else if (walk[i] == 'e') east++;
else if (walk[i] == 'w') west++;
};
if ((north == south) && (west == east)) return true;
return false;
};
// Test cases provided by Codewars
console.log(isValidWalk(['n','s','n','s','n','s','n','s','n','s']), 'should return true');
console.log(isValidWalk(['w','e','w','e','w','e','w','e','w','e','w','e']), 'should return false');
console.log(isValidWalk(['w']), 'should return false');
console.log(isValidWalk(['n','n','n','s','n','s','n','s','n','s']), 'should return false');