Skip to content

Commit

Permalink
refactor(grid-iterators): dedupe interleave logic/iteration, add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Jun 19, 2024
1 parent 3c11a44 commit 7bc9f7f
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 14 deletions.
23 changes: 13 additions & 10 deletions packages/grid-iterators/src/interleave.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,8 @@ export interface InterleaveOpts2D extends GridIterOpts2D {
*
* @param opts -
*/
export function* interleaveColumns2d(opts: InterleaveOpts2D) {
const { cols, rows, tx } = __opts(opts);
const step = (opts.step != null ? opts.step : 2) | 0;
for (let j = 0; j < step; j++) {
yield* map((p) => tx(p[1], p[0]), range2d(0, rows, j, cols, 1, step));
}
}
export const interleaveColumns2d = (opts: InterleaveOpts2D) =>
__interleave(opts, [0, 1], [1, 0]);

/**
* Similar to {@link interleaveColumns2d}, but yields 2D grid coordinates in
Expand All @@ -49,10 +44,18 @@ export function* interleaveColumns2d(opts: InterleaveOpts2D) {
*
* @param opts -
*/
export function* interleaveRows2d(opts: InterleaveOpts2D) {
export const interleaveRows2d = (opts: InterleaveOpts2D) =>
__interleave(opts, [1, 0], [0, 1]);

export function* __interleave(
opts: InterleaveOpts2D,
order: [number, number],
[x, y]: [number, number]
) {
const { cols, rows, tx } = __opts(opts);
const step = (opts.step != null ? opts.step : 2) | 0;
const step = (opts.step ?? 2) | 0;
const [outer, inner] = order.map((x) => [cols, rows][x]);
for (let j = 0; j < step; j++) {
yield* map((p) => tx(p[0], p[1]), range2d(0, cols, j, rows, 1, step));
yield* map((p) => tx(p[x], p[y]), range2d(0, inner, j, outer, 1, step));
}
}
18 changes: 18 additions & 0 deletions packages/grid-iterators/test/interleave.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { expect, test } from "bun:test";
import { interleaveColumns2d, interleaveRows2d } from "../src/index.js";

test("interleaveColumns2d", () => {
expect(
[...interleaveColumns2d({ cols: 4, rows: 6, step: 3 })].join(" | ")
).toEqual(
"0,0 | 0,1 | 0,2 | 0,3 | 0,4 | 0,5 | 3,0 | 3,1 | 3,2 | 3,3 | 3,4 | 3,5 | 1,0 | 1,1 | 1,2 | 1,3 | 1,4 | 1,5 | 2,0 | 2,1 | 2,2 | 2,3 | 2,4 | 2,5"
);
});

test("interleaveRows2d", () => {
expect(
[...interleaveRows2d({ cols: 4, rows: 6, step: 3 })].join(" | ")
).toEqual(
"0,0 | 1,0 | 2,0 | 3,0 | 0,3 | 1,3 | 2,3 | 3,3 | 0,1 | 1,1 | 2,1 | 3,1 | 0,4 | 1,4 | 2,4 | 3,4 | 0,2 | 1,2 | 2,2 | 3,2 | 0,5 | 1,5 | 2,5 | 3,5"
);
});
4 changes: 0 additions & 4 deletions packages/grid-iterators/test/main.test.ts

This file was deleted.

0 comments on commit 7bc9f7f

Please sign in to comment.