All files / day2 puzzle1.js

100% Statements 39/39
100% Branches 4/4
100% Functions 5/5
100% Lines 39/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 652x   2x 50x 50x 50x     2x 220x 220x     2x 218x 218x 218x 218x 940x 940x 940x   2377x 2377x 2377x   940x   218x     2x 2x 2x 2x 2x 105x 105x 105x 455x 1156x 107x       105x 48x         2x 2x 48x   2x     2x            
const { readFile } = require('../helpers/file')
 
const extractGameID = (gameLine) => {
  const extractIdRegexp = new RegExp('(?<=Game\\s)\\d+', 'gm')
  const matches = [...gameLine.match(extractIdRegexp)]
  return parseInt(matches[0])
}
 
const removeGameInfos = (gameLine) => {
  const removeGameInfosRegExp = new RegExp('Game\\s\\d*:\\s+', 'gm')
  return gameLine.replace(removeGameInfosRegExp, '')
}
 
const extractGameResults = (gameLine) => {
  const colorInfos = removeGameInfos(gameLine)
  const games = colorInfos.split(';')
  const formatedArray = []
  for (const game of games) {
    const items = game.split(',')
    const obj = {}
    for (let ball of items) {
      // Remove last and first space that can be in string
      ball = ball.replace(/\s+$/, '').replace(/^\s+/, '')
      const colorValuePair = ball.split(' ')
      obj[colorValuePair[1]] = parseInt(colorValuePair[0])
    }
    formatedArray.push(obj)
  }
  return formatedArray
}
 
const resolvePuzzle = (filePath) => {
  const puzzle = readFile(filePath)
  const possibleGamesId = []
  const MAX_VALUES = { red: 12, green: 13, blue: 14 }
  for (const line of puzzle) {
    const results = extractGameResults(line)
    let isValidLine = true
    for (const result of results) {
      Object.entries(result).forEach(([key, value]) => {
        if (MAX_VALUES[key] < value) {
          isValidLine = false
        }
      })
    }
    if (isValidLine === true) {
      possibleGamesId.push(extractGameID(line))
    }
  }
 
  // Calculate the sum of ids
  let sum = 0
  for (const id of possibleGamesId) {
    sum += id
  }
  return sum
}
 
module.exports = {
  extractGameResults,
  removeGameInfos,
  extractGameID,
  resolvePuzzle,
}