Skip to content

Instantly share code, notes, and snippets.

@akhilstanis
Created October 9, 2020 18:07
Show Gist options
  • Save akhilstanis/084ebfbd87616e0456bcc630d00b02cb to your computer and use it in GitHub Desktop.
Save akhilstanis/084ebfbd87616e0456bcc630d00b02cb to your computer and use it in GitHub Desktop.
// Requires >= TS 4.1
type Put<Board, Player extends ('O' | 'X'), Position> = Board extends `
${infer P0} ${infer P1} ${infer P2}
${infer P3} ${infer P4} ${infer P5}
${infer P6} ${infer P7} ${infer P8}
` ? `
${Position extends P0 ? Player : P0} ${Position extends P1 ? Player : P1} ${Position extends P2 ? Player : P2}
${Position extends P3 ? Player : P3} ${Position extends P4 ? Player : P4} ${Position extends P5 ? Player : P5}
${Position extends P6 ? Player : P6} ${Position extends P7 ? Player : P7} ${Position extends P8 ? Player : P8}
` : never
type Won<A,B,C> = (A | B | C) extends 'X' ? 'X won'
: (A | B | C) extends 'O' ? 'O won'
: never
type Evaluate<Board> = Board extends `
${infer P0} ${infer P1} ${infer P2}
${infer P3} ${infer P4} ${infer P5}
${infer P6} ${infer P7} ${infer P8}
` ? Won<P0,P1,P2> | Won<P3,P4,P5> | Won<P6,P7,P8> | Won<P0,P3,P6> | Won<P1,P4,P7> | Won<P2,P5,P8> | Won<P0,P4,P8> | Won<P2,P4,P6>
: never
type Play<Board,Player extends ('O' | 'X'),Position> = Evaluate<Put<Board,Player,Position>> extends never
? Put<Board,Player,Position>
: Evaluate<Put<Board,Player,Position>>
type B0 = `
0 1 2
3 4 5
6 7 8
`;
type B1 = Play<B0,'X','0'>
type B2 = Play<B1,'X','4'>
type B3 = Play<B2,'X','8'> // X Won
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment