For context, this is for the classic battleships game.
I have a gameboard grid array like so:
[[null, null, null, null, null],
[null, null, null, null, null],
[null, null, null, null, null],
[null, null, null, null, null],
[null, null, null, null, null]],
I'm attempting to place a ship object in the array. The object consists of some properties, such as the ship's name, it's length and it's index (so that the position the ship is hit can be marked on the ship object). For example, a ship placed on the first row might look like this:
[null, {name: 'boat' , index: 0 }, {name: 'boat' , index: 1 }, null, null]
I want to achieve this using functional programming principles and avoid mutating the array, which is what I'm currently doing (i.e. using for loops and setting array[x][y] = {ship}).
I understand that the best way of achieving this is by using map().
Since the array is 2 dimensional I am nesting two maps together. My function so far looks like this:
const placeShip = (ship, x, y) => {
if (grid[x][y] !== null) return;
const newGrid = grid.map((row, indexX) => row.map((element, indexY) => {
if (indexX === x && indexY === y) {
{
name: ship.name,
index: XXX
} // how to insert the index position?
}
}
return newGrid
}
The trouble I am experiencing is twofold. Firstly, I can't figure out how I can correctly insert the ship's index position in the object using the nested map. This was easy enough using for loops as they begin at 0 and end at ship.length.
Secondly, I'm going wrong somewhere and my function is not returning a 2d array with any objects in it, I am just receiving undefined.
Where am I going wrong?
Thanks
return. That's all.how to insert the index position?it's not clear what index you are referring to. What should that value be? A single number? a array with x, y coords?undefineds. Which is also going to cause your conditional check at the beginning to have false positives on subsequent calls.