I am passing a Array of Arrays (2d array) to a function that not only makes a copy original along with my attempts to copy from the original outside of the function, but the references hold.
Have been assuming it has something to do with the fact that the inner arrays are never explicitly “removed” from reference, but if it’s a stupid typo, I apologize.
-made an AoA > dat
-copied it to > cpy
-passed to a function that edits the elements of a copy of cpy.
-dat is somehow affected
-wtf?
// may cause headache.
const copy = arr => [...(arr.slice())].slice();
const spiral = (grid, start = [0, 0]) => {
if (!Array.isArray(grid) || !Array.isArray(grid[0]) || grid.length < 2 || grid[0].length < 2) return grid;
let dir = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0]
],
corners = [
[0, grid[0].length - 1],
[grid.length - 1, grid[0].length - 1],
[grid.length - 1, 0],
[1, 0]
],
size = grid.length * grid[0].length,
indx = 0,
stepi = 0,
step = dir[stepi],
result = copy(grid), // <------+
[r, c] = start; // |-----------{ the two culprit lines perhaps?
while (size--) { // | { the rows are probably making it
result[r][c] = indx++; // <------+ { through by reference.
if (r === corners[stepi][0] && c === corners[stepi][1]) {
if (stepi === 3)
corners = corners.map((e, i) =>
[e[0] + [1, -1, -1, 1][i], e[1] + [-1, -1, 1, 1][i]]);
stepi = (stepi + 1) % 4;
step = dir[stepi];
}
r = r + step[0];
c = c + step[1];
}
return result;
}
// can't seperate this 2d array from the reference for some reason.
//suspect it's because of the inner arrays, but still seems rediculous.
const dat = Array.from(new Array(5),
(_, i) => Array.from(new Array(5),
(__, j) => 5 * i + j));
console.log('array dat is correct here.');
console.log(dat);
// this nasty peice of work is just an attempt to divorce from original array.
let val = [...copy([...dat].slice().reduce((a, c) => [...a, c], []))];
let cpy = spiral(val);
console.log('cpy is completely modified')
console.log(cpy);
console.log('only copies of dat have made it all the way to cpy, right?')
console.log(dat);
console.log('nyooope. what the actual piss? are the inner arrays being fed straight through by reference?');
/* ================================output=================================================
array dat is correct here.
dat = [
[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]
]
only copies of dat have made it all the way to ref, right ?
cpy = [
[0, 1, 2, 3, 4],
[15, 16, 17, 18, 5],
[14, 23, 24, 19, 6],
[13, 22, 21, 20, 7],
[12, 11, 10, 9, 8]
]
nyooope.what the actual piss ? are the inner arrays being fed straight through by reference ?
dat = [
[0, 1, 2, 3, 4],
[15, 16, 17, 18, 5],
[14, 23, 24, 19, 6],
[13, 22, 21, 20, 7],
[12, 11, 10, 9, 8]
]
*/