I'm making a puzzle game that relies on elements being placed in grids and evaluating the values at certain x,y locations. My data is stored in 2d arrays, so regular maps don't work that well. As a result, I made this helper function to map over every single cell in a 2d array.
// makes transformations on the cell level in a 2d array
export const twoDMap = (twoDimensionalArray, mapFunction) => {
return twoDimensionalArray.map((row, y) => {
return row.map(mapFunction);
})
}
This works fine most of the time, except when I need to use the x,y indexes of a cell in my 2d map. In the test case below, I can't seem to access the y value of the cells. (I got rid of the ES6 syntax so it'll run in the console)
var testArray = [[true, "random-string", 3],
["potato", false, 4],
[null, 4, 5]];
function twoDMap(twoDimensionalArray, mapFunction) {
return twoDimensionalArray.map(function (row, y) {
return row.map(mapFunction);
})
}
function logCells(cells) {
twoDMap(cells ,function(cell, x) {
console.log(cell, "location: ", x);
// console.log(cell, "location: ", x, y); //throws an error
})
}
logCells(testArray);
I'm pretty sure I need to make some kind of change to twoDMap, and it's probably quite minor, but I've been on this problem for hours and still can't get it to work. When I write it out manually (using regular nested maps instead of twoDMap ), it works fine, but it's overly verbose and I'd like to avoid it considering that it's a common pattern in this project. This is the common suggestion that I keep finding whenever I google this problem, but it's not a viable solution given how much nesting I need to do for this project.
Essentially, I'm looking for a way to modify twoDMap or the callbacks that are sent into it, so that my callbacks can access the x and y indexes of the 2d array sent to twoDMap.
row.map, you could alter this to accept theyas another param, and then pass this to the callback so that mapFunction callback get's the Y,.. But I must say all this looks very convoluted to access a 2d array.row.map? I've tried different things and nothing's given me the result I was looking for so far. In some cases it's super easy to access the arrays (array[y][x]), but in this case the 2d arrays are of variable shapes and sizes (flattening them won't yield consistent results).