Advent of Code 2022: Day 9

Nibbles, is that you? 🐍

by Amy L

HTML

<link rel="stylesheet" href="https://adventofcode.com/static/style.css?30">
<h1><a href="https://adventofcode.com/2022/day/9" target="_blank">Day 9</a></h1>
<diV class="puzzle-input">
  <label for="INPUT_DATA">Input</label>
  <textarea id="INPUT_DATA" autocomplete="off" placeholder="paste your input here" rows="7" cols="50"></textarea>
</diV>
<dl>
<dt>Part 1</dt>
  <dd>
    <label>Answer:
      <input type="text" id="answer1" readonly />
    </label>
  </dd>
  
  <dt>Part 2</dt>
  <dd>
    <label>Answer:
      <input type="text" id="answer2" readonly />
    </label>
  </dd>
</dl>

JavaScript 1.7

function Day9(input) {
  function solvePart1(motions) {
  	const knots = simulateMultipleKnotsMotions(motions);
		return getUniqueLocationsFromTail(knots);
  }
  function solvePart2(motions) {
  	const knots = simulateMultipleKnotsMotions(motions, 9);
		return getUniqueLocationsFromTail(knots);
  }
  const motions = parseMotions(input);
  const part1 = solvePart1(motions);
  const part2 = solvePart2(motions);
  return {part1,  part2};
  
}
document.addEventListener('DOMContentLoaded', () => {
  getInputData('INPUT_DATA', (input) => {
  	const answers = Day9(input);
    const [answer1El, answer2El] = [
      document.getElementById('answer1'),
      document.getElementById('answer2')
    ];
    answer1El.value = answers.part1;
    answer2El.value = answers.part2;
  });
});

/*******************************************************************
	Utility libs
**/
function parseMotions(input) {
	return input
  	.split('\n')
    .map((line) => {
  		const [direction, distance] = line.split(' ');
      return {direction, distance: parseInt(distance)};
		});
}
function simulateMultipleKnotsMotions(motions, numKnots = 1) {
	const knots = [];
	const head = new Head();
  let	previousKnot = head;
  for (let k = 0; k < numKnots; k++) {
  	let newKnot = new Tail(previousKnot);
  	knots.push(newKnot);
    previousKnot = newKnot;
  }
  //console.log(knots)
  
  motions.forEach((motion) => {
  	//console.log('>>',motion);
    for (let d = 0; d < motion.distance; d++) {
      switch (motion.direction) {
        case 'U':
          head.moveUp();
          break;
        case 'D':
          head.moveDown();
          break;
        case 'L':
          head.moveLeft();
          break;
        case 'R':
          head.moveRight();
          break;
      }
      knots.forEach((knot) => knot.follow());
    }
  });
  return [head, ...knots];
}
function getInputData(inputId, callback) {
  const dataEl = document.getElementById(inputId);
  dataEl.addEventListener('input', () =>...