/** * Parse a list of Cube Bag TM games from strings * @param {string} games A list of strings describing game results * @returns {Game[]} A list of games played */ export function ParseGameStrings(games: string[]): Game[] { const parsedGames: Game[] = []; const gameIDRegex = new RegExp(/Game (\d+)/); const resultsRegex = new RegExp(/(\d+) (red|blue|green)/, "g"); for(const gameString of games) { // Split the game string into its two main parts const [gamePart, setsPart] = gameString.split(": "); // Get the Game ID const gameID = gamePart.match(gameIDRegex); if (gameID == null) { throw new Error(`Failed to parse Game ID\n${gameString}`); } // Create the parsed game object const parsed: Game = { ID: Number(gameID[1]), Sets: [] }; // Split the game's sets into individual units const setStrings = setsPart.split(/; /); // Loop over each of the sets pulled for(const setString of setStrings) { // Match any colors and their amounts pulled in the set const results = setString.matchAll(resultsRegex); if (results == null) { throw new Error(`Failed to parse set results\n${setString}`); } const parsedSet: Set = { red: 0, green: 0, blue: 0 }; for (const result of results) { const amountPulled = Number(result[1]); const colorPulled = result[2]; parsedSet[colorPulled as keyof Set] = amountPulled; } // Add the set to the game parsed.Sets.push(parsedSet); } // Add the game to our complete list parsedGames.push(parsed); } return parsedGames; } /** * A game of Cube Bag TM */ export type Game = { /** * The ID of the game played */ ID: number, /** * A list of the sets played during the game */ Sets: Set[] }; /** * A single set of cubes pulled in a game of Cube Bag */ export type Set = { /** The number of red cubes pulled during the set */ red: number, /** The number of green cubes pulled during the set */ green: number, /** The number of blue cubes pulled during the set */ blue: number, };