Skip to content

Instantly share code, notes, and snippets.

@vlastachu
Created December 24, 2023 11:38
Show Gist options
  • Save vlastachu/6974045a321e123be6543ffa034e5576 to your computer and use it in GitHub Desktop.
Save vlastachu/6974045a321e123be6543ffa034e5576 to your computer and use it in GitHub Desktop.
type Alley = " ";
type MazeItem = "๐ŸŽ„" | "๐ŸŽ…" | Alley;
type DELICIOUS_COOKIES = "๐Ÿช";
type MazeMatrix = MazeItem[][];
type Directions = "up" | "down" | "left" | "right";
type As<From, To> = From extends To? From : never;
type Num = 1[]
type i<num extends Num> = num['length']
type zero = []
type ten = inc<inc<inc<inc<inc<inc<inc<inc<inc<inc<zero>>>>>>>>>>
type inc<i extends Num> = [1, ...i]
type dec<i extends Num> = i extends [1, ...infer rest] ? rest : never
type Coords = [Num, Num]
type zero2 = [zero, zero]
type applyDirection<xy extends Coords, dir extends Directions> =
dir extends 'up' ? [xy[0], dec<xy[1]>] :
dir extends 'down' ? [xy[0], inc<xy[1]>] :
dir extends 'left' ? [dec<xy[0]>, xy[1]] :
dir extends 'right' ? [inc<xy[0]>, xy[1]] : never
type getAt<board extends MazeMatrix, xy extends Coords>
= board[i<xy[1]>][i<xy[0]>]
type setAtList<list extends any[], item, i extends any[], acc extends any[] = [], result extends any[] = []> =
list extends [infer head, ...infer rest]
? acc extends i
? [...result, item, ...rest]
: setAtList<rest, item, i, inc<acc>, [...result, head]>
: never
type setAt<list extends any[][], item, xy extends Coords> =
setAtList<list, setAtList<list[i<xy[1]>], item, xy[0]>, xy[1]>
type findSanta<board extends MazeMatrix, xy extends Coords = zero2>
= getAt<board, xy> extends undefined ? findSanta<board, [zero, inc<xy[1]>]>
: getAt<board, xy> extends '๐ŸŽ…' ? xy : findSanta<board, [inc<xy[0]>, xy[1]]>
type winCondition<xy extends Coords, dir extends Directions> =
dir extends 'up' ? (xy[1] extends zero ? true : false) :
dir extends 'down' ? (xy[1] extends ten ? true : false) :
dir extends 'left' ? (xy[0] extends zero ? true : false) :
dir extends 'right' ? (xy[0] extends ten ? true : false) : never
type Move<board extends MazeMatrix, dir extends Directions> = Move_2<board, dir,findSanta<board>>
type Move_2<board extends MazeMatrix, dir extends Directions, santa extends Coords> =
winCondition<santa, dir> extends true ? MazeWin :
Move_3<board, santa, As<applyDirection<santa, dir>, Coords>>
type Move_3<board extends MazeMatrix, santa extends Coords, destination extends Coords> =
getAt<board, destination> extends Alley
? setAt<As<setAt<board, '๐ŸŽ…', destination>, any[][]>, Alley, santa>
: board
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment