From e17ca18a9e81c463135215eb69b247a57bac88e3 Mon Sep 17 00:00:00 2001 From: Anthony McLin Date: Thu, 14 Dec 2023 18:30:38 -0800 Subject: [PATCH] feat(2023-02): parse game draw data --- 2023/day-02/game.js | 28 +++++++++++++++++++ 2023/day-02/game.test.js | 60 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 2023/day-02/game.js create mode 100644 2023/day-02/game.test.js diff --git a/2023/day-02/game.js b/2023/day-02/game.js new file mode 100644 index 0000000..e985fa1 --- /dev/null +++ b/2023/day-02/game.js @@ -0,0 +1,28 @@ +const parseGame = (gameString) => { + const data = gameString.split(':') + const id = parseInt( + data[0].match(/\d+/)[0] // find the game number + ) + const draws = data[1].split(';') // split the game into draws + .map((draw) => { + const result = ['red', 'green', 'blue'] + .map((color) => { // extract count for each color + const reg = new RegExp(`\\d+(?= ${color})`) + console.debug(reg) + const val = draw.match(reg) || [0] + console.debug(`${color} ${val}`) + return parseInt(val).toString(16).padStart(2, '0') // convert to hex + }) + + return result.join('') // combine into a RGB hex color string + }) + + return { + id, + draws + } +} + +module.exports = { + parseGame +} diff --git a/2023/day-02/game.test.js b/2023/day-02/game.test.js new file mode 100644 index 0000000..33987d1 --- /dev/null +++ b/2023/day-02/game.test.js @@ -0,0 +1,60 @@ +/* eslint-env mocha */ +const { expect } = require('chai') +const { parseGame } = require('./game') + +describe('--- Day 2: Cube Conundrum ---', () => { + describe('Part 1', () => { + describe('parseGame', () => { + it('extracts a game string into a data object with RGB hex values for draws', () => { + const data = [ + 'Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green', + 'Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue', + 'Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red', + 'Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red', + 'Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green' + ] + const result = [ + { + id: 1, + draws: [ + '040003', + '010206', + '000200' + ] + }, { + id: 2, + draws: [ + '000201', + '010304', + '000101' + ] + }, { + id: 3, + draws: [ + '140806', + '040d05', + '010500' + ] + }, { + id: 4, + draws: [ + '030106', + '060300', + '0e030f' + ] + }, { + id: 5, + draws: [ + '060301', + '010202' + ] + } + ] + + data.forEach((game, idx) => { + expect(parseGame(game)).to.deep.equal(result[idx]) + }) + }) + }) + }) +})