@thi.ng/grid-iterators
Version: 
2D grid and shape iterators w/ multiple orderings
38 lines (37 loc) • 884 B
JavaScript
import { asInt } from "@thi.ng/api/typedarray";
function* hline(x, y, len) {
  [x, y, len] = asInt(x, y, len);
  for (const xmax = x + len; x < xmax; x++) {
    yield [x, y];
  }
}
function* vline(x, y, len) {
  [x, y, len] = asInt(x, y, len);
  for (const ymax = y + len; y < ymax; y++) {
    yield [x, y];
  }
}
function* hlineClipped(x, y, len, left, top, right, bottom) {
  [x, y, len] = asInt(x, y, len);
  if (x >= right || y < top || y >= bottom) return;
  if (x < left) {
    len += x - left;
    x = left;
  }
  yield* hline(x, y, Math.min(len, right - x));
}
function* vlineClipped(x, y, len, left, top, right, bottom) {
  [x, y, len] = asInt(x, y, len);
  if (x < left || x >= right || y >= bottom) return;
  if (y < top) {
    len += y - top;
    y = top;
  }
  yield* vline(x, y, Math.min(len, bottom - y));
}
export {
  hline,
  hlineClipped,
  vline,
  vlineClipped
};