import fs from "fs"; const input = fs.readFileSync("./input.txt").toString(); const digits = [ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", ]; const re = new RegExp(`(${digits.join("|")}|\\d)`); const invertedRe = new RegExp( `(${digits .map((digit) => digit.split("").reverse().join("")) .join("|")}|\\d)`, ); function parseNumber(s: string) { return s.length === 1 ? Number(s) : digits.findIndex((digit) => digit === s) + 1; } const result = input .split("\n") .slice(0, -1) .map((line) => [ line.match(re)?.[0] || "", // Reverse the string, find the inverted match right-to-left and reverse again line .split("") .reverse() .join("") .match(invertedRe)?.[0] .split("") .reverse() .join("") || "", ]) .reduce((acc, value) => { if (!value[0].length || !value[1].length) throw new Error("Match failed"); return ( acc + parseNumber(value[0]) * 10 + parseNumber(value[value.length - 1]) ); }, 0); console.log({ result });