Skip to content

Commit

Permalink
Pass hex into initializing function
Browse files Browse the repository at this point in the history
  • Loading branch information
butzopower committed Jan 1, 2022
1 parent 78ac12f commit 0abf540
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/hexgrid.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export class Hex<T = void> {
private readonly parent: HexGrid<T>;
private readonly x: number;
private readonly y: number;
readonly x: number;
readonly y: number;
content: T | undefined;

constructor(parent: HexGrid<T>, x: number, y: number) {
Expand All @@ -21,13 +21,13 @@ export class HexGrid<T = void> {
constructor(
width: number,
height: number,
initializeFn?: () => T,
initializeFn?: (hex: Hex<T>) => T,
) {
this.hexArray = Array.from(new Array(height))
.map((_, y) => Array.from(new Array(width))
.map((_, x) => {
const hex = new Hex(this, x, y);
hex.content = initializeFn ? initializeFn() : undefined;
hex.content = initializeFn ? initializeFn(hex) : undefined;
return hex;
}));
}
Expand Down
14 changes: 14 additions & 0 deletions tests/hexgrid.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,20 @@ describe('a hex grid', () => {
expect(grid.at(0, 0).content).to.eql(thing);
}));
});

it('passes the initializing hex to the initialize function', () => {
const grid = new HexGrid<string>(3, 3, (hex) => `${hex.x},${hex.y}`);

expect(grid.at(0, 0).content).to.eql('0,0');
expect(grid.at(1, 0).content).to.eql('1,0');
expect(grid.at(2, 0).content).to.eql('2,0');
expect(grid.at(0, 1).content).to.eql('0,1');
expect(grid.at(1, 1).content).to.eql('1,1');
expect(grid.at(2, 1).content).to.eql('2,1');
expect(grid.at(0, 2).content).to.eql('0,2');
expect(grid.at(1, 2).content).to.eql('1,2');
expect(grid.at(2, 2).content).to.eql('2,2');
});
});
});

Expand Down

0 comments on commit 0abf540

Please sign in to comment.