- Joined
- Dec 7, 2022
- Messages
- 5
- Reaction score
- 0
My assignment is to implement the getLocation function, that accepts 2 parameters:
For example, we have the coordinates = [2, 1] and commands = ['left', 'back', 'back'] arrays:
My function:
function getLocation(coordinates, commands) {
let x = coordinates[0];
let y = coordinates[1];
let newArr = [];
for(let i = 0; i <= commands; i++){
if(commands === 'forward'){
newArr.push(y + 1);
}else if(commands === 'back'){
newArr.push(y - 1);
}else if(commands === 'right'){
newArr.push(x + 1);
}else if(commands === 'left'){
newArr.push(x - 1);
};
};
return newArr;
};
If i try to use the function with coordinates = 1, 2, commands = 'right' for example, it should return 2, 2,but it returns an empty array.
- coordinates — the array of initial coordinates in the [x, y] form;
- commands — the array with command history in the ['command1', 'command2', 'command3' ...] form.
- 'forward' means y + 1;
- 'back' means y - 1;
- 'right' means x + 1;
- 'left' means x - 1.
For example, we have the coordinates = [2, 1] and commands = ['left', 'back', 'back'] arrays:
- coordinates after the first command — [1, 1] (1 step left);
- coordinates after the second command — [1, 0] (1 step back);
- coordinates after the third command — [1, -1] (1 step back);
- the result is the [1, -1] array.
My function:
function getLocation(coordinates, commands) {
let x = coordinates[0];
let y = coordinates[1];
let newArr = [];
for(let i = 0; i <= commands; i++){
if(commands === 'forward'){
newArr.push(y + 1);
}else if(commands === 'back'){
newArr.push(y - 1);
}else if(commands === 'right'){
newArr.push(x + 1);
}else if(commands === 'left'){
newArr.push(x - 1);
};
};
return newArr;
};
If i try to use the function with coordinates = 1, 2, commands = 'right' for example, it should return 2, 2,but it returns an empty array.