Skip to content

Instantly share code, notes, and snippets.

@jjclxrk
Last active December 2, 2023 04:17
Show Gist options
  • Select an option

  • Save jjclxrk/880d12b2d470506605245ea0ffa13462 to your computer and use it in GitHub Desktop.

Select an option

Save jjclxrk/880d12b2d470506605245ea0ffa13462 to your computer and use it in GitHub Desktop.
[aoc2023] - 01b.mjs
import fs from "fs";
import readline from "readline";
const digitPattern = "([0-9]|one|two|three|four|five|six|seven|eight|nine)";
// Pattern capturing the first and last "digit" if a line has multiple
// matches.
const linePatternMultiple = new RegExp(`${digitPattern}.*${digitPattern}.*`);
// Pattern capturing the first occurrence of a "digit". Intended to be used
// as a fallback if the `linePatternMultiple` produces no match (because
// there is only one "digit" in the line).
const linePatternSingle = new RegExp(digitPattern);
const parseDigit = (digit) => {
switch (digit.toLowerCase()) {
// According to the problem spec, "zero" isn't listed as a valid digit.
case "0":
return 0;
case "1":
case "one":
return 1;
case "2":
case "two":
return 2;
case "3":
case "three":
return 3;
case "4":
case "four":
return 4;
case "5":
case "five":
return 5;
case "6":
case "six":
return 6;
case "7":
case "seven":
return 7;
case "8":
case "eight":
return 8;
case "9":
case "nine":
return 9;
default:
throw new Error(`Unparseable digit: ${digit}`);
}
};
const parseLine = (line) => {
const match = linePatternMultiple.exec(line) ?? linePatternSingle.exec(line);
if (!match) {
console.error(`Unparseable line: ${line}`);
}
const first = match[1];
// If `linePatternSingle` produced the match, there will only be one match.
const last = match[2] ?? match[1];
try {
return parseDigit(first) * 10 + parseDigit(last);
} catch (error) {
console.error(`Unparseable digit in line: ${line}`);
console.error(error.message);
process.exit(1);
}
};
const fileStream = fs.createReadStream("input.txt");
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity,
});
let sum = 0;
rl.on("line", (line) => {
sum += parseLine(line);
});
rl.on("close", () => {
console.log("result:", sum);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment