common.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import fs from "node:fs";
  2. /**
  3. * Load the input for a day's challenge
  4. *
  5. * @param {string|number} dayNumber The number of the day to load. A string for a file path can be provided here too.
  6. * @param {Function} parsingFunction A function to parse the input to a usable format
  7. * @param {boolean} literalPath If true, the {@link dayNumber} value should be used as a file path
  8. *
  9. * @returns {unknown}
  10. */
  11. export function loadInput(dayNumber, parsingFunction, literalPath = false) {
  12. let filePath = literalPath ? dayNumber : `./inputs/day_${dayNumber}.input`;
  13. const data = fs.readFileSync(filePath, "utf8");
  14. return typeof parsingFunction == "function" ? parsingFunction(data) : data;
  15. }
  16. /**
  17. * Comparator for sorting numbers into ascending order
  18. *
  19. * @param {number} a
  20. * @param {number} b
  21. *
  22. * @returns {-1|0|1}
  23. */
  24. export function numericAscSort(a, b) {
  25. return clamp(a - b);
  26. }
  27. /**
  28. * Convert a string to an integer
  29. *
  30. * Does no checks to make sure the value is actually a number-like value
  31. *
  32. * @param {string} string
  33. *
  34. * @returns {number}
  35. */
  36. export function strToInt(string) {
  37. return parseInt(string, 10);
  38. }
  39. /**
  40. * Clamp a number between two other numbers
  41. *
  42. * @param {number} value The value to be clamped
  43. * @param {number} min The minimum value
  44. * @param {number} max The maximum value
  45. *
  46. * @returns {number} The clamped value
  47. */
  48. export function clamp(value, min = -1, max = 1) {
  49. return Math.max(min, Math.min(max, value));
  50. }
  51. /**
  52. * Deep clone a value
  53. *
  54. * @param {any} value
  55. *
  56. * @returns {any}
  57. */
  58. export function deepClone(value) {
  59. return JSON.parse(JSON.stringify(value));
  60. }