import { promises as fsPromises } from "fs"; async function asyncReadFile(filename) { try { const contents = await fsPromises.readFile(filename, "utf-8"); const arr = contents.split(/\r?\n/); return arr; } catch (err) { console.error(err); } } // dial 0-99 const DIAL_START = 50; const Dial = (start = DIAL_START) => { let countZero = 0, current = start; const getCountZero = () => countZero, reset = () => { countZero = 0; current = start; }, rotate = (initialVal = "") => { const val = initialVal.trim(), dir = val.length ? val.substring(0, 1).toUpperCase() : "", amount = val.length ? (val.substring(1) * 1) % 100 : 0; if (!dir) { console.log(`${val} => invalid value!`); } const initial = current; if (dir === "R") { current = (current + amount) % 100; } else if (dir === "L") { current = (current - amount + (current - amount < 0 ? 100 : 0)) % 100; } console.log( `${val} => rotating ${ dir === "R" ? "RIGHT" : "LEFT" } ${amount} from ${initial} to ${current}` ); if (current === 0) { countZero++; console.log("CountZero!"); } }; return { getCountZero, reset, rotate, }; }; const dial = Dial(); /* // Test Data const dataToParse = [ "L68", "L30", "R48", "L5", "R60", "L55", "L1", "L99", "R14", "L82", ]; */ const dataToParse = await asyncReadFile("../input.txt"); dataToParse.forEach((val) => { if (val.trim()) dial.rotate(val); }); console.log(`Final countZero is ${dial.getCountZero()}`);