2_common.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * Parse a list of Cube Bag TM games from strings
  3. * @param {string} games A list of strings describing game results
  4. * @returns {Game[]} A list of games played
  5. */
  6. export function ParseGameStrings(games: string[]): Game[] {
  7. const parsedGames: Game[] = [];
  8. const gameIDRegex = new RegExp(/Game (\d+)/);
  9. const resultsRegex = new RegExp(/(\d+) (red|blue|green)/, "g");
  10. for(const gameString of games) {
  11. // Split the game string into its two main parts
  12. const [gamePart, setsPart] = gameString.split(": ");
  13. // Get the Game ID
  14. const gameID = gamePart.match(gameIDRegex);
  15. if (gameID == null) {
  16. throw new Error(`Failed to parse Game ID\n${gameString}`);
  17. }
  18. // Create the parsed game object
  19. const parsed: Game = {
  20. ID: Number(gameID[1]),
  21. Sets: []
  22. };
  23. // Split the game's sets into individual units
  24. const setStrings = setsPart.split(/; /);
  25. // Loop over each of the sets pulled
  26. for(const setString of setStrings) {
  27. // Match any colors and their amounts pulled in the set
  28. const results = setString.matchAll(resultsRegex);
  29. if (results == null) {
  30. throw new Error(`Failed to parse set results\n${setString}`);
  31. }
  32. const parsedSet: Set = {
  33. red: 0,
  34. green: 0,
  35. blue: 0
  36. };
  37. for (const result of results) {
  38. const amountPulled = Number(result[1]);
  39. const colorPulled = result[2];
  40. parsedSet[colorPulled as keyof Set] = amountPulled;
  41. }
  42. // Add the set to the game
  43. parsed.Sets.push(parsedSet);
  44. }
  45. // Add the game to our complete list
  46. parsedGames.push(parsed);
  47. }
  48. return parsedGames;
  49. }
  50. /**
  51. * A game of Cube Bag TM
  52. */
  53. export type Game = {
  54. /**
  55. * The ID of the game played
  56. */
  57. ID: number,
  58. /**
  59. * A list of the sets played during the game
  60. */
  61. Sets: Set[]
  62. };
  63. /**
  64. * A single set of cubes pulled in a game of Cube Bag
  65. */
  66. export type Set = {
  67. /** The number of red cubes pulled during the set */
  68. red: number,
  69. /** The number of green cubes pulled during the set */
  70. green: number,
  71. /** The number of blue cubes pulled during the set */
  72. blue: number,
  73. };