UNPKG

@thi.ng/grid-iterators

Version:

2D grid and shape iterators w/ multiple orderings

73 lines (72 loc) 1.53 kB
import { assert } from "@thi.ng/errors/assert"; import { __opts } from "./utils.js"; function* diagonalSlopeY(opts) { const { cols, rows, tx } = __opts(opts); const maxX = cols - 1; const slope = opts.slope | 0; assert(slope > 0, "slope must be > 0"); const num = cols * rows - 1; let x = 0; let y = 0; let nx = Math.min(1, maxX); let ny = nx > 0 ? 0 : slope; let n = slope; const reset = () => { n = slope; x = nx; y = ny; if (nx < maxX) nx++; else ny += slope; }; for (let i = 0; i <= num; i++) { yield tx(x, y); if (--n > 0) { y++; if (y >= rows) reset(); } else { x--; y++; if (x < 0 || y >= rows) reset(); else n = slope; } } } function* diagonalSlopeX(opts) { const { cols, rows, tx } = __opts(opts); const maxX = cols - 1; const slope = opts.slope | 0; assert(slope > 0, "slope must be > 0"); const num = cols * rows - 1; let x = Math.min(slope - 1, maxX); let y = 0; let n = x + 1; let nx = Math.min(x + slope, maxX); let ny = nx > 0 ? 0 : slope; const reset = () => { x = nx; y = ny; if (nx < maxX) { nx = Math.min(nx + slope, maxX); n = slope; } else { ny++; n = x % slope + 1; } }; for (let i = 0; i <= num; i++) { yield tx(x, y); if (--n > 0) { x--; if (x < 0) reset(); } else { x--; y++; if (x < 0 || y >= rows) reset(); else n = slope; } } } export { diagonalSlopeX, diagonalSlopeY };