Skip to content

Instantly share code, notes, and snippets.

@mansour-ahmed
Last active February 24, 2024 20:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mansour-ahmed/52584ea15b9e40da6270ddbfb95ba1f9 to your computer and use it in GitHub Desktop.
Save mansour-ahmed/52584ea15b9e40da6270ddbfb95ba1f9 to your computer and use it in GitHub Desktop.
A function to calculate possible coordinates for a knight on a chess board.
type Coordinate = [number, number];
/**
* @desc gets all possible coordinates for a knight given its current position
* @param x knight's current x position
* @param y knight's current y position
*
* @example possibleDestinations(4, 3) => [[3, 1], [3, 5], [5, 5], [5, 1], [2, 2], [2, 4], [6, 2], [6, 4]]
*
* @returns all possible coordinates for the knight
*/
const possibleDestinations = (x: number, y: number): Coordinate[] => {
if (!isValidCoordinate([x, y])) {
throw new Error("Invalid chess board position");
}
return KNIGHT_POSSIBLE_L_MOVES.map<Coordinate>(([xMove, yMove]) => [
xMove + x,
yMove + y,
]).filter(isValidCoordinate);
};
const KNIGHT_POSSIBLE_L_MOVES: Coordinate[] = [
[-1, -2],
[-1, 2],
[1, 2],
[1, -2],
[-2, -1],
[-2, 1],
[2, -1],
[2, 1],
];
const isValidCoordinate = (coordinate: Coordinate) =>
coordinate.every(isValidChessBoardPosition);
const CHESS_BOARD_LOWER_BOUND = 0;
const CHESS_BOARD_UPPER_BOUND = 7;
const isValidChessBoardPosition = (position: number) =>
position >= CHESS_BOARD_LOWER_BOUND &&
position <= CHESS_BOARD_UPPER_BOUND &&
position % 1 === 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment