@thi.ng/grid-iterators
Version:
2D grid and shape iterators w/ multiple orderings
32 lines (31 loc) • 674 B
JavaScript
import { __opts } from "./utils.js";
function* zigzagDiagonal2d(opts) {
const { cols, rows, tx } = __opts(opts);
const num = cols * rows - 1;
for (let x = 0, y = 0, ny = 0, dx = -1, dy = 1, d = 0, down = true, i = 0; i <= num; i++) {
yield tx(x, y);
if (i !== num) {
do {
if (y === ny) {
if (down) {
y++;
d++;
ny = 0;
} else {
x++;
ny = ++d;
}
down = !down;
dx *= -1;
dy *= -1;
} else {
x += dx;
y += dy;
}
} while (x >= cols || y >= rows);
}
}
}
export {
zigzagDiagonal2d
};