diff --git a/src/grid/grid.ts b/src/grid/grid.ts index 62d49720..8bdd6b88 100644 --- a/src/grid/grid.ts +++ b/src/grid/grid.ts @@ -1,19 +1,21 @@ -import { createHex, Hex, HexCoordinates, toString } from '../hex' +import { createHex, Hex, HexCoordinates } from '../hex' import { NoopMap } from './noopMap' import { rectangle, RectangleOptions } from './traversers' -import { eachCallbackFn, GetOrCreateHexFn, GetPrevHexesFn, mapCallbackFn, Traverser } from './types' +import { eachCallbackFn, GetOrCreateHexFn, GetPrevHexesFn, GridStore, mapCallbackFn, Traverser } from './types' export class Grid { - static of(hexPrototype: T, store?: Map, getPrevHexes?: GetPrevHexesFn) { + static of(hexPrototype: T, store?: GridStore, getPrevHexes?: GetPrevHexesFn) { return new Grid(hexPrototype, store, getPrevHexes) } - getOrCreateHex: GetOrCreateHexFn = (coordinates) => - this.store.get(toString(coordinates)) ?? createHex(this.hexPrototype).clone(coordinates) // clone to enable users to make custom hexes + getOrCreateHex: GetOrCreateHexFn = (coordinates) => { + const hex = createHex(this.hexPrototype).clone(coordinates) // clone to enable users to make custom hexes + return this.store.get(hex.toString()) ?? hex + } constructor( public hexPrototype: T, - public store: Map = new NoopMap(), + public store: GridStore = new NoopMap(), private getPrevHexes: GetPrevHexesFn = () => [], ) {} @@ -78,7 +80,7 @@ export class Grid { const traverse: GetPrevHexesFn = () => { const nextHexes: T[] = [] - let cursor = Array.from(this.getPrevHexes()).pop() || createHex(this.hexPrototype).clone() // clone to enable users to make custom hexes + let cursor = Array.from(this.getPrevHexes()).pop() ?? createHex(this.hexPrototype).clone() // clone to enable users to make custom hexes for (const traverser of traversers) { for (const nextCursor of traverser(cursor, this.getOrCreateHex)) { diff --git a/src/grid/types.ts b/src/grid/types.ts index 058ce6f0..870473e4 100644 --- a/src/grid/types.ts +++ b/src/grid/types.ts @@ -16,3 +16,7 @@ export interface GetOrCreateHexFn { export type eachCallbackFn = (value: T, grid: Grid) => void export type mapCallbackFn = (value: T, grid: Grid) => T + +export interface GridStore { + get(id: string): T | undefined +}