I have a 2D array (grid) of 2D arrays (chunks) for a game I'm developing:
const c1 = [[1, 2],
[3, 4]]
const c2 = [[5, 6],
[7, 8]]
const c3 = [[9, 0],
[1, 2]]
const c4 = [[3, 4],
[5, 6]]
const grid_of_chunks = [[c1, c2],
[c3, c4]];
and I want to reduce/flatten the grid_of_chunks to:
[[1, 2, 5, 6],
[3, 4, 7, 8],
[9, 0, 3, 4],
[1, 2, 5, 6]]
I've been able to implement a functional solution for this (in 2 lines of Clojure), but I'm struggling to wrap my head around translating it to functional JavaScript, and bridging the gap between the two language's map semantics (JS map only accepts one array, whereas Clojure's map accepts many collections...).
This is as far as I got:
function join_grid_of_chunks(gofc) {
const joined_horiz = gofc.map(
gofc_row => [].map.apply(gofc_row, [cs => [].concat.apply(cs)])
);
return [].concat.apply(joined_horiz);
}
Edit: Clojure solution (which works for uniformly-sized square chunks, in an arbitrarily sized square grid):
(defn join-grid-of-chunks [gofc]
(let [joined (map #(apply map concat %) gofc)]
(apply concat joined)))
Here's what I have:
const c1 = [[1, 2], [3, 4]];
const c2 = [[5, 6], [7, 8]];
const c3 = [[9, 0], [1, 2]];
const c4 = [[3, 4], [5, 6]];
const grid_of_chunks = [
[c1, c2],
[c3, c4]
];
function transform(input) {
return input.flatMap(rows => {
return rows.reduce((result, chunk) => {
chunk.forEach((row, rowIndex) => {
result[rowIndex] = result[rowIndex] || [];
result[rowIndex].push(...row);
});
return result;
}, []);
});
}
console.log(transform(grid_of_chunks));
Should work for NxN chunks and MxM grid
A more general solution using flatMap is to map over the indices from the first chunk of each grid row.
function joinGridOfChunks(grid) {
return grid.flatMap(row => row[0].map((_, i) => row.flatMap(chunk => chunk[i])))
}
With a zip function (such as the one in lodash), you could write it slightly more elegantly as:
function zip(...arrays) {
return arrays[0].map((_, i) => arrays.map(arr => arr[i]))
}
function joinChunks(chunks) { // Horizontally join an array of chunks e.g. [[[1,2],[3,4]], [[5,6],[7,8]]] --> [[1,2,5,6],[3,4,7,8]]
return zip(...chunks).map(row => row.flat())
}
console.log(gridOfChunks.flatMap(joinChunks));
zip plus map seems to be close to Clojure's map with multiple collections. This should work for any shape 2d chunks in a 2d grid.