43 lines
910 B
TypeScript
43 lines
910 B
TypeScript
export interface State {
|
|
board: ('X' | 'O' | null)[][]
|
|
}
|
|
|
|
export const initial: State = {
|
|
board: [
|
|
[null, null, null],
|
|
[null, null, null],
|
|
[null, null, null],
|
|
]
|
|
}
|
|
|
|
export interface BaseAction {
|
|
type: string
|
|
}
|
|
export interface PlayAction extends BaseAction {
|
|
type: 'play'
|
|
row: number
|
|
column: number
|
|
mark: 'X' | 'O'
|
|
}
|
|
export interface ResetAction extends BaseAction {
|
|
type: 'reset'
|
|
}
|
|
export type Action = PlayAction | ResetAction
|
|
|
|
export function reducer(state: State, action: Action): State {
|
|
switch (action.type) {
|
|
case 'play':
|
|
const playAction = action as PlayAction
|
|
return {
|
|
board: state.board.map((row, rIdx) =>
|
|
rIdx !== playAction.row ? row : row.map((cell, cIdx) =>
|
|
cIdx !== playAction.column ? cell : playAction.mark
|
|
)
|
|
)
|
|
}
|
|
case 'reset':
|
|
return initial
|
|
}
|
|
//throw new Error('Unknown action type')
|
|
}
|