common.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import * as fs from "fs";
  2. import * as readline from "readline";
  3. import * as util from "util";
  4. export async function LoadInput(dayNumber: number): Promise<string[]> {
  5. const contents = [];
  6. const stream = fs.createReadStream(`./inputs/${dayNumber}.txt`, "utf8");
  7. const rl = readline.createInterface({
  8. input: stream,
  9. crlfDelay: Infinity,
  10. });
  11. for await (const line of rl) {
  12. contents.push(line);
  13. }
  14. return contents;
  15. }
  16. /**
  17. * Inspect a variable in the console
  18. *
  19. * @param {any} value A value to inspect
  20. */
  21. export function Inspect(value: any): void {
  22. console.log(util.inspect(value, { breakLength: Infinity, colors: true, depth: 256 }));
  23. }
  24. /**
  25. * Deep clone any input
  26. *
  27. * @param {any} value A value to clone
  28. * @returns A clone of the input
  29. */
  30. export function DeepClone(value: any): any {
  31. return JSON.parse(JSON.stringify(value));
  32. }
  33. /**
  34. * Extracts all numbers from a string
  35. *
  36. * If there were no numbers in the string, then an empty array is returned.
  37. *
  38. * Numbers in the output are in the order they appeared in in the input
  39. *
  40. * @param {string} str A string
  41. * @returns {number[]} An array of numbers
  42. */
  43. export function ExtractNumbers(str: string): number[] {
  44. return str.split(/[^\-0-9]/).filter((n) => n.length).map((n) => Number(n));
  45. }
  46. /**
  47. * Check if an array only contains one unique value
  48. *
  49. * @see https://stackoverflow.com/a/14438954/2708601
  50. * @param arr An array of any type
  51. * @returns Whether the array only contains duplicates or not
  52. */
  53. export function ArrayIsOnlyDuplicates(arr: Array<any>): boolean {
  54. if (arr.length === 1) { return true; }
  55. return arr.filter((val, idx, array) => {
  56. return array.indexOf(val) === idx;
  57. }).length == 1;
  58. }
  59. /**
  60. * Sum all values in an array
  61. *
  62. * @param arr The array to sum
  63. * @returns The sum of all elements in the array
  64. */
  65. export function SumArray(arr: number[]): number {
  66. return arr.reduce((accumulator, value) => accumulator += value, 0);
  67. }