DEV Community

SnowBit
SnowBit

Posted on

Day 2 Solution in JavaScript - Advent of Code 2021

In this article I will be going to show you a solution of Day 2 of Advent of Code 2021 in JavaScript.

Let's get started,

  • Let's get the input

const fs = require('fs')
const input = fs.readFileSync('input.txt').toString()

const inputArray = input.split('\n').map(command => command.split(' ')).map(command => [command[0], +command[1]])
Enter fullscreen mode Exit fullscreen mode
  • For part 1
// First Part

const position = {horizonatal: 0, depth: 0}

for (const [command, value] of inputArray) {
  switch(command){
    case 'forward':
      position.horizonatal += value
      break;

    case 'down':
      position.depth += value;
      break

    case 'up':
    position.depth -= value
    break

    default:
      console.log('invalid', command, value)
      break
  }
}

console.log(position.horizonatal * position.depth)
Enter fullscreen mode Exit fullscreen mode
  • For Part 2

Discussion (0)