summaryrefslogtreecommitdiffstats
path: root/day18/day18-2.js
blob: d6f6e58964ff84469fa52c64e06503df875c7496 (plain) (blame)
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
const data = require('./data')
const lines = data.split(/\n/g).filter(Boolean)

const ev = (str) => {
  let spl = str.split(' ')
  while(spl.length) {
    spl = [eval(spl.slice(0, 3).join(''))].concat(spl.slice(3))
  }
  return spl[0]
}

const evPlus = (str) => {
  while (/\+/.test(str)) {
    str = str.replace(/(\d+) \+ (\d+)/g, (match, n1, n2) => parseInt(n1) + parseInt(n2))
  }
  return eval(str)
}

const evPar = (str, ev) => {
  while(/\(/.test(str)) {
    str = str.replace(/\(([^()]+)\)/g, (match, par) => ev(par))
  }
  return ev(str)
}

let sum = 0
lines.forEach(l => sum += evPar(l, evPlus))
console.log('Answer: ', sum)