Skip to content

Commit

Permalink
fix(grid): grid's update() now always returns a grid that iterates ov…
Browse files Browse the repository at this point in the history
…er hexes in its store

Previously the grid returned from update() iterated over hexes in the grid instance where update()
was called on. These hexes may be different from those in the grid instance returned from update().

fixes #68
  • Loading branch information
flauwekeul committed Apr 22, 2021
1 parent cb6c65d commit b2a0298
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
26 changes: 24 additions & 2 deletions src/grid/grid.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,17 +167,19 @@ describe('update()', () => {
})

test('creates a clone of the grid and passes it to the callback', () => {
const hexes = [createHex(hexPrototype, { q: 1, r: 2 }), createHex(hexPrototype, { q: 3, r: 4 })]
const newStore = new Map()
const callback = jest.fn((grid) => {
expect(grid.hexes()).toEqual(hexes)
grid.store = newStore
return grid
})
const grid = new Grid(hexPrototype, [at({ q: 1, r: 2 }), at({ q: 3, r: 4 })])
const grid = new Grid(hexPrototype, () => hexes)
const result = grid.update(callback)

expect(callback).toBeCalledWith(expect.any(Grid))
expect(callback.mock.calls[0][0]).not.toBe(grid)
expect(result.hexes()).toEqual(grid.hexes())
expect(result.hexes()).toEqual([])
expect(result.store).not.toBe(grid.store)
expect(result.store).toBe(newStore)
expect(result).not.toBe(grid)
Expand All @@ -194,6 +196,26 @@ describe('update()', () => {
expect(result.store).toBe(newStore)
expect(result).not.toBe(grid)
})

test('iterates over the hexes *in the store* of the cloned grid', () => {
interface TestHex extends Hex {
test: number
}
const hexPrototype = createHexPrototype<TestHex>()
const hex1 = createHex(hexPrototype, { q: 0, r: 0, test: 1 })
const hex2 = hex1.clone({ test: 2 })
const grid1 = new Grid(hexPrototype, () => [hex1]).filter((hex) => hex.test === 0)

const grid2 = grid1.update((grid) => {
grid.store.set(hex2.toString(), hex2)
})

grid2
.each((hex) => {
expect(hex).toEqual(hex2)
})
.run()
})
})

describe('each()', () => {
Expand Down
7 changes: 5 additions & 2 deletions src/grid/grid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,11 @@ export class Grid<T extends Hex> {
}

update(callback: (grid: Grid<T>) => Grid<T> | void) {
const nextGrid = this._clone(this._getPrevHexes)
return callback(nextGrid) || nextGrid
let nextGrid = this._clone(this._getPrevHexes)
nextGrid = callback(nextGrid) || nextGrid
// reset hex state to iterate over nextGrid's store (fixes issue #68)
nextGrid._getPrevHexes = () => Array.from(nextGrid.store.values())
return nextGrid
}

each(callback: Callback<T, void>) {
Expand Down

0 comments on commit b2a0298

Please sign in to comment.