Skip to content

Commit

Permalink
1st step: Introduced the sorting option of the game history.
Browse files Browse the repository at this point in the history
  • Loading branch information
Mrcel97 committed Aug 24, 2018
1 parent 61d218a commit f9a7c74
Showing 1 changed file with 36 additions and 8 deletions.
44 changes: 36 additions & 8 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ class Game extends React.Component {
}],
stepNumber: 0,
xIsNext: true,
order: 'desc',
}
}

Expand Down Expand Up @@ -46,6 +47,20 @@ class Game extends React.Component {
});
}

handleSwap() {
if (this.state.history[this.state.history.length - 1].lastPush != null) {
if(this.state.order === 'desc') {
this.setState({
order: 'asc',
});
return;
}
this.setState({
order: 'desc',
});
}
}

jumpTo(step) {
this.winner = null;
this.setState({
Expand All @@ -54,6 +69,25 @@ class Game extends React.Component {
});
}

loadMoves() {
var orderedHistory = this.history.sort((a,b) => a.key > b.key).map((step, move) => {
const desc = move ? 'Go to move #' + move : 'Go to game start';
return (
<li key={move}>
<button onClick={() => this.jumpTo(move)}>{desc}</button>
</li>
);
});

if (this.state.order === 'asc') {
orderedHistory.sort((a,b) => a.key < b.key)
} else {
orderedHistory.sort((a,b) => a.key > b.key)
}

return orderedHistory;
}

render() {
const MAX_LEN = 9;
let winnerResult;
Expand All @@ -62,14 +96,7 @@ class Game extends React.Component {
this.positions = this.history[this.state.stepNumber];
winnerResult = calculateWinner(this.current.squares);

const moves = this.history.map((step, move) => {
const desc = move ? 'Go to move #' + move : 'Go to game start';
return (
<li key={move}>
<button onClick={() => this.jumpTo(move)}>{desc}</button>
</li>
);
});
const moves = this.loadMoves();

const coordinates = this.history.map((step, pos) => {
if (!step.coordinates[step.lastPush]) { return null; }
Expand Down Expand Up @@ -103,6 +130,7 @@ class Game extends React.Component {
</div>
<div className="game-info">
<div>{status}</div>
<button onClick={this.handleSwap.bind(this)}>Reorder Log</button>
<ol>{moves}</ol>
</div>
<div className="game-info">
Expand Down

0 comments on commit f9a7c74

Please sign in to comment.