Skip to content

Commit

Permalink
feat(grid): reimplement traverse to not be a generator
Browse files Browse the repository at this point in the history
This performs slightly better. Also added option `returnWhenOutOfBounds` (defaults to false) to stop
traversing when going outside the grid boundaries. This can significantly improve performance.
  • Loading branch information
flauwekeul committed Jul 23, 2022
1 parent f0fe5cc commit 3a7a09e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 14 deletions.
27 changes: 15 additions & 12 deletions src/grid/grid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,18 +93,21 @@ export class Grid<T extends Hex> implements Iterable<T> {
return obj
}

// todo: implement without using generator (probably?)
// *traverse(traversers: Traverser<T> | Traverser<T>[]): HexGenerator<T> {
// // todo: add to docs that this function starts at the first hex in grid.#hexes
// // todo: not sure about this though
// const [cursor] = this.#hexes.values()
// yield cursor

// for (const hex of concat(traversers)(this.createHex, cursor)) {
// const existingHex = this.getHex(hex)
// if (existingHex) yield existingHex
// }
// }
// enabling stopWhenOutOfBounds can improve performance significantly
traverse(traversers: Traverser<T> | Traverser<T>[], { stopWhenOutOfBounds = false } = {}): T[] {
const hexes: T[] = []

for (const hex of concat(traversers)(this.createHex)) {
const existingHex = this.getHex(hex)
if (existingHex) {
hexes.push(existingHex)
} else if (stopWhenOutOfBounds) {
return hexes
}
}

return hexes
}

clone(): Grid<T> {
const clonedHexes = new Map<string, T>()
Expand Down
2 changes: 0 additions & 2 deletions src/grid/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ export interface Traverser<T extends Hex, R extends Iterable<T> = Iterable<T>> {
(createHex: (coordinates?: HexCoordinates) => T, cursor?: HexCoordinates): R
}

export type HexGenerator<T extends Hex> = Generator<T, void, void>

export enum Rotation {
CLOCKWISE = 'CLOCKWISE',
COUNTERCLOCKWISE = 'COUNTERCLOCKWISE',
Expand Down

0 comments on commit 3a7a09e

Please sign in to comment.