chess-board/src/validate.ts

80 lines
2.4 KiB
TypeScript

import { COLORS, PIECES, FILES, RANKS, BoardState } from "./Board";
const COLORS_AS_STRINGS: string[] = COLORS.map((color) => color as string);
const PIECES_AS_STRINGS: string[] = PIECES.map((piece) => piece as string);
const FILES_AS_STRINGS: string[] = FILES.map((file) => file as string);
const RANKS_AS_NUMBERS: number[] = RANKS.map((rank) => rank as number);
const validateBoardState = (input: unknown): BoardState | null => {
if (typeof (input) !== "object" || Array.isArray(input) || input === null) {
console.error("Input is not keyed object");
return null;
}
const hasInvalidShape = Object.entries(input).some(([file, ranks]) => {
if (typeof (file) !== "string") {
console.error("file is not string");
return true;
}
if (!FILES_AS_STRINGS.includes(file)) {
console.error("file is not included in valid files")
return true;
}
if (typeof (ranks) !== "object" || Array.isArray(ranks) || ranks === null) {
console.error("ranks is not a keyed object");
return true;
}
return Object.entries(ranks).some(([rank, pieces]) => {
if (typeof (rank) !== "string") {
console.error("rank is not a string");
return true;
}
if (!RANKS_AS_NUMBERS.includes(Number(rank))) {
console.error("rank is not included in valid ranks");
return true;
}
if (typeof (pieces) !== "object" || Array.isArray(pieces) || pieces === null) {
console.error("piece state is not a keyed object");
return true;
}
return Object.entries(pieces).some(([key, value]) => {
if (typeof (key) !== "string") {
console.error("piece key is not a string");
return true;
}
if (!["kind", "color"].includes(key)) {
console.error("piece key is not included in valid keys")
return true;
}
if (key === "kind" && (typeof (value) !== "string" || !PIECES_AS_STRINGS.includes(value))) {
console.error("kind's value is not a string, or not a valid piece");
return true;
} else if (key === "color" && (typeof (value) !== "string" || !COLORS_AS_STRINGS.includes(value))) {
console.error("colors' value is not a string, or not a valid color");
return true;
}
return false;
});
});
});
if (hasInvalidShape) {
return null;
}
return input as BoardState;
};
export {
validateBoardState,
};