Skip to content

Commit

Permalink
逆順にする処理
Browse files Browse the repository at this point in the history
  • Loading branch information
na8esin committed May 24, 2024
1 parent 1b65d24 commit bc6ff00
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 19 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,6 @@ function handlePlay(nextSquares: (string | null)[]) {
setCurrentMove(nextHistory.length - 1);
}
```

## 単純に関数に切り出すとパフォーマンスが悪くなったりしない?
flutterで問題になるやつ
50 changes: 33 additions & 17 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ type History = (string | null)[][];
export default function Game() {
const [history, setHistory] = useState<History>([Array(9).fill(null)]);
const [currentMove, setCurrentMove] = useState(0);
const [onOff, setOnOff] = useState(true);
const xIsNext = currentMove % 2 === 0;
const currentSquares = history[currentMove];

Expand All @@ -88,6 +89,35 @@ export default function Game() {
setCurrentMove(nextMove);
}

function handleToggle() {
setOnOff(!onOff);
}

const moves = historyToMoves(history, currentMove, jumpTo, onOff);

return (
<div className="game">
<div className="game-board">
<Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />
</div>
<div className="game-info">
<div style={{ paddingInlineStart: '40px' }}>
<Toggle onToggle={handleToggle} />
</div>
<ol>
{moves}
</ol>
</div>
</div>
);
}

// 単純に関数に抽出してみた
function historyToMoves(
history: (string | null)[][],
currentMove: number, jumpTo: (move: number) => void,
onOff: boolean
): JSX.Element[] {
const moves = history.map((_, move) => {
const descriptionButton = (move > 0)?
'Go to move #' + move:
Expand All @@ -105,26 +135,12 @@ export default function Game() {
}
</li>
);
})
});

return (
<div className="game">
<div className="game-board">
<Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />
</div>
<div className="game-info">
<div style={{ paddingInlineStart: '40px' }}>
<Toggle />
</div>
<ol>
{moves}
</ol>
</div>
</div>
);
return onOff ? moves : moves.reverse();
}

function calculateWinner(squares: (string | null)[]): string | null{
function calculateWinner(squares: (string | null)[]): string | null {
const lines = [
[0, 1, 2],
[3, 4, 5],
Expand Down
4 changes: 2 additions & 2 deletions src/Toggle.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import styles from './toggle.module.css';

export default function Toggle() {
export default function Toggle({onToggle}: {onToggle: () => void}){
return (
<label className={styles.toggleButton}>
<input type="checkbox"/>
<input type="checkbox" onChange={onToggle} />
</label>
)
}

0 comments on commit bc6ff00

Please sign in to comment.