DEV Community

Cover image for Advent of code - Day 18
Quentin Ménoret
Quentin Ménoret

Posted on

1

Advent of code - Day 18

Are you participating in the Advent of code this year?

If you don't know what the advent of code is, it's a website where you'll find a daily challenge (every day it gets harder). It's a really fun event, you should participate!

I try to solve the exercises using either JavaScript or TypeScript and will share my solutions daily (with one day delay so no one can cheat!). I only share the solution for the second part.

This one was super fun! I't just a question of priorities and RegEx, but it took me a while to have it working properly.

Not going to lie, I took the easy way and used eval to calculate the expression as soon as I had them in the right order!

Here is my solution for day #18:

function run(str) {
  // + operations
  if (str.match(/\d+ \+ \d+/)) {
    const substr = /\d+ \+ \d+/.exec(str)[0]
    return run(str.replace(substr, eval(substr)))
  }
  // if there is a number alone in a parenthesis, remove the parenthesis
  if (str.match(/\(\d+\)/)) {
    const aloneNumber = /\(\d+\)/.exec(str)[0]
    return run(str.replace(aloneNumber, aloneNumber.slice(1, -1)))
  }
  // otherwise extract the content of a parenthesis
  if (str.match(/\(\d+( [\*,\+] \d+)+\)/)) {
    const parenthesisContent = /\(\d+( [\*,\+] \d+)+\)/.exec(str)[0]
    return run(str.replace(parenthesisContent, run(parenthesisContent.slice(1, -1))))
  }
  return eval(str)
}

console.log(input.reduce((acc, str) => acc + run(str), 0))
Enter fullscreen mode Exit fullscreen mode

Feel free to share your solution in the comments!


Photo by Markus Spiske on Unsplash

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay