Skip to content

Commit

Permalink
refactor(grid-iterators): update diagonalEnds2d()
Browse files Browse the repository at this point in the history
- add `all` option to include first & last points
  • Loading branch information
postspectacular committed Mar 25, 2023
1 parent d94ad6d commit e20bf7b
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 6 deletions.
11 changes: 6 additions & 5 deletions packages/grid-iterators/src/diagonal-ends.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,24 @@ import { diagonal2d } from "./diagonal.js";
import { __opts } from "./utils.js";

/**
* Filtered version of {@link diagonal2d}, only including end points of
* the diagonals, apart from the very first and last points: `[0,0]` and
* `[cols-1, rows-1]`.
* Filtered version of {@link diagonal2d}, only including end points of the
* diagonals. Unless `all` option is enabled (default: false), the very first
* and last points are skipped, i.e. `[0,0]` and `[cols-1, rows-1]`.
*
* @remarks
* `cols` and `rows` MUST be both >= 2.
*
* @param opts -
*/
export function* diagonalEnds2d(opts: GridIterOpts) {
export function* diagonalEnds2d(opts: GridIterOpts & { all: boolean }) {
const { cols, rows, tx } = __opts(opts);
const num = cols * rows - 1;
const maxX = cols - 1;
const maxY = rows - 1;
const check = opts.all ? (i: number) => i > 0 && i < num : () => true;
let i = 0;
for (let p of diagonal2d({ cols, rows })) {
if (i > 0 && i < num) {
if (check(i)) {
const [x, y] = p;
if (x === 0 || x === maxX || y === 0 || y === maxY) yield tx(x, y);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/grid-iterators/src/diagonal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export function* diagonal2d(opts: GridIterOpts) {
const num = cols * rows - 1;
for (let x = 0, y = 0, nx = 1, ny = 0, i = 0; i <= num; i++) {
yield tx(x, y);
if (i != num) {
if (i !== num) {
do {
if (y === ny) {
y = 0;
Expand Down

0 comments on commit e20bf7b

Please sign in to comment.