Advertisement
scibuff

Advent of Code 2023 - Day 20 - Parser

Dec 20th, 2023
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.15 KB | Source Code | 0 0
  1. const LOW_PULSE = "low";
  2. const HIGH_PULSE = "high";
  3.  
  4. const parse = (input) => {
  5.   const lines = utils.getInputLines(input);
  6.   const modules = {};
  7.   const inputMap = {};
  8.   const rxInputs = [];
  9.   for (let line of lines) {
  10.     const parts = line.split("->");
  11.     const label = parts[0].trim() == "broadcaster" ? "broadcaster" : parts[0].trim().substring(1);
  12.     const type = parts[0].trim().charAt(0);
  13.     const destinations = parts[1].trim().split(", ");
  14.     if (destinations.includes("rx")) {
  15.       rxInputs.push(label);
  16.     }
  17.     for (const d of destinations) {
  18.       if (!inputMap[d]) {
  19.         inputMap[d] = [];
  20.       }
  21.       inputMap[d].push(label);
  22.     }
  23.     modules[label] = {
  24.       label: label,
  25.       type: type,
  26.       destinations: destinations,
  27.     };
  28.     if (type == "%") {
  29.       modules[label].on = false;
  30.     }
  31.   }
  32.   for (const label of Object.keys(inputMap)) {
  33.     const module = modules[label];
  34.     if (module?.type == "&") {
  35.       module.inputs = inputMap[label].reduce((o, label) => {
  36.         o[label] = LOW_PULSE;
  37.         return o;
  38.       }, {});
  39.     }
  40.   }
  41.   return {
  42.     modules: modules,
  43.     rxInputs: rxInputs,
  44.   };
  45. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement