idx(x, y, z)
This is a helper function that solves a key problem in spatial programming: JavaScript arrays are 1D, but we think in 3D. The formula x + N * (y + N * z) is the standard way to map any 3D coordinate to a unique 1D position. Understanding this is essential for working with grids in any dimension.
function idx(x, y, z) { return x + N * (y + N * z); }
Line-by-line explanation (1 lines)
return x + N * (y + N * z);- Converts 3D coordinates (x, y, z) into a single 1D array index. Since JavaScript arrays are 1D, this formula linearizes the 3D grid: the z-layer is multiplied by N², then the y-row by N, then x is added. This lets us store a 3D cube in a 1D array.