Skip to content

Commit

Permalink
feat(grid): add GridStore type and make sure the toString() Hex metho…
Browse files Browse the repository at this point in the history
…d is called to create an id

A store for a grid only needs to implement a get() method, not the entire Map interface
  • Loading branch information
flauwekeul committed Apr 22, 2021
1 parent a5f7acc commit 99192b2
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
16 changes: 9 additions & 7 deletions src/grid/grid.ts
Original file line number Diff line number Diff line change
@@ -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<T extends Hex> {
static of<T extends Hex>(hexPrototype: T, store?: Map<string, T>, getPrevHexes?: GetPrevHexesFn<T>) {
static of<T extends Hex>(hexPrototype: T, store?: GridStore<T>, getPrevHexes?: GetPrevHexesFn<T>) {
return new Grid<T>(hexPrototype, store, getPrevHexes)
}

getOrCreateHex: GetOrCreateHexFn<T> = (coordinates) =>
this.store.get(toString(coordinates)) ?? createHex(this.hexPrototype).clone(coordinates) // clone to enable users to make custom hexes
getOrCreateHex: GetOrCreateHexFn<T> = (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<string, T> = new NoopMap(),
public store: GridStore<T> = new NoopMap(),
private getPrevHexes: GetPrevHexesFn<T> = () => [],
) {}

Expand Down Expand Up @@ -78,7 +80,7 @@ export class Grid<T extends Hex> {

const traverse: GetPrevHexesFn<T> = () => {
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)) {
Expand Down
4 changes: 4 additions & 0 deletions src/grid/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,7 @@ export interface GetOrCreateHexFn<T extends Hex> {
export type eachCallbackFn<T extends Hex> = (value: T, grid: Grid<T>) => void

export type mapCallbackFn<T extends Hex> = (value: T, grid: Grid<T>) => T

export interface GridStore<T extends Hex> {
get(id: string): T | undefined
}

0 comments on commit 99192b2

Please sign in to comment.