1_1.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { LoadInput } from "../common.ts";
  2. /**
  3. * Calculate the sum of all calibration values in a document
  4. *
  5. * @param {string[]} document All lines of a document containing calibration values
  6. * @returns {number} The sum of all calibration values found in a document
  7. */
  8. function CalculateCalibrationSum(document: string[]): number {
  9. return document.reduce((register, currVal) => register + extractCalibrationValue(currVal), 0);
  10. }
  11. /**
  12. * Extract a calibration value from a line of text
  13. *
  14. * Extracts the first and last digit from a string of text,
  15. * concatenates the two, and returns this as the calibration value.
  16. *
  17. * If only one digit is present, the one digit is concatenated to
  18. * itself.
  19. *
  20. * @param {string} line The line of text to extract the calibration value out of
  21. * @returns {number} The two-digit calibration value hidden in that string
  22. */
  23. function extractCalibrationValue(line: string): number {
  24. const digitsInString = line.replace(/\D/g, "");
  25. return Number(digitsInString[0] + digitsInString[digitsInString.length - 1]);
  26. }
  27. const tests: string[] = [
  28. "1abc2",
  29. "pqr3stu8vwx",
  30. "a1b2c3d4e5f",
  31. "treb7uchet"
  32. ];
  33. const input = await LoadInput(1);
  34. console.log("Test Cases");
  35. console.log("Expected: 142", `Actual: ${CalculateCalibrationSum(tests)}`);
  36. console.log("Input");
  37. console.log(`Your calibration sum ${CalculateCalibrationSum(input)}`);