Skip to content

Instantly share code, notes, and snippets.

@morintd
Created March 11, 2024 19:56
Show Gist options
  • Save morintd/4d534caca9cb776b03a539e321f35c7c to your computer and use it in GitHub Desktop.
Save morintd/4d534caca9cb776b03a539e321f35c7c to your computer and use it in GitHub Desktop.
import { useCallback, useMemo, useState } from "react";
import { GameDomainModel } from "./game.domain-model";
import { JumpTo } from "./use-cases/jump-to.use-case";
import { Play } from "./use-cases/play.use-case";
import { useDependencyContext } from "../common/dependency-context";
import { IGamePresenter } from "./ports/game-presenter.port";
export function useGameController(
defaultGame: GameDomainModel.GameState,
presenter: IGamePresenter
) {
const dependencies = useDependencyContext();
const [currentGame, setCurrentGame] =
useState<GameDomainModel.GameState>(defaultGame);
const useCases = useMemo(() => {
return {
jumpTo: new JumpTo(dependencies.board),
play: new Play(dependencies.board),
};
}, [dependencies.board]);
const onPlay = useCallback(
(square: number) => {
useCases.play
.execute({ step: currentGame.step, square })
.then((game) => setCurrentGame(game));
},
[currentGame.step, useCases.play]
);
const onJumpTo = useCallback(
(step: number) => {
useCases.jumpTo.execute({ step }).then((game) => setCurrentGame(game));
},
[useCases.jumpTo]
);
const { status, moves, squares } = useMemo(() => {
return presenter.format({
history: currentGame.history,
step: currentGame.step,
winner: currentGame.winner,
xIsNext: currentGame.xIsNext,
});
}, [currentGame, presenter]);
return {
squares,
status,
moves,
onPlay,
onJumpTo,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment