import {StorageCoordinates} from "../state/Coordinates"; import {areCellsEquivalent, EMPTY_CELL, getCell, HexCell, HexMap} from "../state/HexMap"; import {MapAction} from "../actions/MapAction"; import {CELL_COLOR, CELL_REMOVE} from "../actions/CellAction"; export function updateCell(map: HexMap, coords: StorageCoordinates, newData: Partial): HexMap { const oldCell = getCell(map, coords) || EMPTY_CELL; return replaceCell(map, coords, { ...oldCell, ...newData, }) } export function replaceCell(oldMap: HexMap, {line, cell}: StorageCoordinates, newCell: HexCell|null): HexMap { if (areCellsEquivalent(getCell(oldMap, {line, cell}), newCell)) { return oldMap } const oldLines = oldMap.layer const oldLine = oldLines[line] const newLine = [ ...oldLine.slice(0, cell), newCell, ...oldLine.slice(cell + 1) ] const newLines = [ ...oldLines.slice(0, line), newLine, ...oldLines.slice(line + 1) ] return { ...oldMap, layer: newLines } } export function hexMapReducer(oldState: HexMap, action: MapAction): HexMap { switch (action.type) { case CELL_COLOR: return updateCell(oldState, action.at, { color: action.color }) case CELL_REMOVE: return replaceCell(oldState, action.at, null) } }