22 lines
841 B
JavaScript
22 lines
841 B
JavaScript
// m05 game: one `update` function turns every action into a new state; replay is a fold over actions.
|
|
import { turn } from './rules.js'
|
|
import { tick } from './spawn.js'
|
|
|
|
/** Tick and Turn are handled here; other actions leave the state alone (m10 adds more). */
|
|
export const update = (state, action) => {
|
|
switch (action.tag) {
|
|
case 'Tick': return tick(state)
|
|
case 'Turn': return turn(state, action.dir)
|
|
default: return state
|
|
}
|
|
}
|
|
|
|
/** Fold the actions over the state, left to right. */
|
|
export const replay = (state, actions) => actions.reduce(update, state)
|
|
|
|
/** Like replay, but keeps each intermediate state. Recursion instead of mutation: no array is ever pushed to. */
|
|
export const history = (state, actions) =>
|
|
actions.length === 0
|
|
? [state]
|
|
: [state, ...history(update(state, actions[0]), actions.slice(1))]
|