Skip to content

Commit

Permalink
simplified time travel function
Browse files Browse the repository at this point in the history
  • Loading branch information
ldgit committed Dec 10, 2018
1 parent 7de165d commit 808410c
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 31 deletions.
26 changes: 6 additions & 20 deletions src/ultimate-game.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,12 @@ function updateBoardActiveStatus(boardIndex, squareIndex) {
};
}

function timeTravel(oldState, { pointInHistory }) {
const newState = deepCopyGameState(oldState);
newState.pointInHistory = pointInHistory;
newState.nextPlayer = pointInHistory % 2 === 0 ? 'X' : 'O';

return newState;
function timeTravel(state, { pointInHistory }) {
return {
...state,
pointInHistory,
nextPlayer: pointInHistory % 2 === 0 ? 'X' : 'O',
};
}

function getInitialState() {
Expand All @@ -104,20 +104,6 @@ function getInitialState() {
};
}

function deepCopyGameState(state) {
const newHistory = state.history.map(boardEntry => ({ boards: deepCopyGameBoards(boardEntry.boards) }));

return {
...state,
nextPlayer: state.nextPlayer,
history: newHistory,
};
}

function deepCopyGameBoards(boards) {
return boards.map(board => ({ ...board, isActive: board.isActive, squares: [...board.squares] }));
}

function nextBoardIsWon(boards, { squareIndex }) {
return !!calculateWinner(boards[squareIndex].squares);
}
Expand Down
11 changes: 0 additions & 11 deletions test/ultimate-game.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -250,17 +250,6 @@ describe('ultimate tic-tac-toe', () => {
assert.equal(callTimeTravel(secondMoveState, { pointInHistory: 1 }).nextPlayer, 'O');
});

it('should return a deep copy of input state', () => {
const newState = callPlaySquare(initialState, { boardIndex: 1, squareIndex: 8 });

const stateAfterTimeTravel = callTimeTravel(newState, { pointInHistory: 0 });

stateAfterTimeTravel.pointInHistory = 1984;
stateAfterTimeTravel.history[0].boards[4].squares[1] = 'modified in state returned by time travel, should not be in previus state';
assert.strictEqual(newState.pointInHistory, 1, 'time travel must return a *copy* of input state');
expect(newState.history[0].boards[4].squares[1]).to.equal(null, 'time travel must return a *deep copy* of input state');
});

it(
'when time traveling to past and then playing a move, should discard all history after that time travel point',
() => {
Expand Down

0 comments on commit 808410c

Please sign in to comment.