If I have a 4x4 2d Array and want to work on a specific column, I can either get it using a map and set it back or I can get a shallow copy of it and work directly on the original array values.
The get/set way
// create the original array
let arr = [...Array(4)].map(e => Array(4).fill(0))
console.log(arr)
// get a specific column, e.g. the 3d
let myColumn = arr.map(tile => tile[3])
// change it
myColumn[2] = 1
// set it back
arr.map((line, i) => line[3] = myColumn[i])
console.log("modified array", arr)
UPDATE
Here are my (ugly) getter/setter functions, probably very perfectible. It does not even properly deep copy in each case (e.g. the get with index > 11
) but it still does the job.
const getLine = (index) => {
if (index < 4) return field.map(fieldLine => fieldLine[index])
if (index > 3 && index < 8) return field[index - 4].slice().reverse()
if (index > 7 && index < 12) return field.map(fieldLine => fieldLine[Math.abs(index - 11)]).slice().reverse()
if (index > 11) return field.slice()[Math.abs(index - 15)]
}
const setLine = (index, line) => {
if (index < 4) field.map((fieldLine, i) => fieldLine[index] = line[i])
if (index > 3 && index < 8) field[index - 4] = line.reverse()
if (index > 7 && index < 12) field.slice().reverse().map((fieldLine, i) => fieldLine[Math.abs(index - 11)] = line[i])
if (index > 11) field[Math.abs(index - 15)] = line
}
FYI, the original problem is here: https://www.codewars.com/kata/4-by-4-skyscrapers