I have some task to resolve, when we need to renew the coordinates array from commands, like this.
when forward – y is adding 1, back – y minus 1, right – x plus 1 and left – x minus 1. But something is not working properly here.
function getLocation(coordinates, commands) {
// write code here
let x = coordinates[0]
let y = coordinates[1]
//let newCoordinates = [];
for (let i = 0; i < commands.length; i++) {
if (i === 'forward' ) {
y += 1 ;
}
if (i === 'back') {
y -= 1 ;
}
if (i === 'right') {
x += 1;
}
if (i === 'left') {
x -= 1;
}
}
//newCoordinates.push(x, y)
return coordinates;
}
console.log(getLocation([0, 0], ['forward', 'forward', 'left']))
2
Answers
You are using index for checking the command, you should use values of array in conditional statement like this
You’re not accessing the values in the
commands
array when looping. At the moment you’re comparing if thei
is either'forward'
,'back'
, or any other command.What you should be doing is comparing each value in the
commands
array by accessing the value.commands[i] === 'forward'
, and so forth.Returning the
coordinates
array will not give you the updated values, as modifyingx
andy
don’t update the values in thecoordinates
array. The easiest way to solve this by returning a new array withx
andy
in it, like so:return [x, y];
I also took the liberty to modify your function to use a destructuring assignment and a rest parameter as an example on how you could implement the function in a different way. Don’t know if it will help you out, but I assume you’re still learning and this might expand your knowledge base.