Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

runSolution / readData could allow raw input data #5

Open
scarletczen opened this issue Dec 3, 2024 · 0 comments
Open

runSolution / readData could allow raw input data #5

scarletczen opened this issue Dec 3, 2024 · 0 comments

Comments

@scarletczen
Copy link

scarletczen commented Dec 3, 2024

For solutions like the day-3 advent of code, we don't need the split('\n') function while reading the file. What if we could pass in an options object to the runSolution function like

await runSolution(day3a, { rawInput: true });

to allow more freedom to handle the input file. (we could allow for the readFile options to be passed in as well)

The file in question-> packages/ts-aoc-starter/src/generators/preset/generator.ts
The function in question runSolution and readData()

For now, I've modified the utils function as follows

import chalk from 'chalk';
import { readFile } from 'fs/promises';
import { join } from 'path';

export async function runSolution(
  solution: (data: string[] | Buffer) => Promise<unknown>,
  options?: {
    rawInput: boolean;
  }
) {
  const data = await readData(options);
  const answer = await solution(data);
  console.log(chalk.bgGreen('Your Answer:'), chalk.green(answer));
}

export async function readData(options?: { rawInput: boolean }) {
  const [_, fullPath, dataSet] = process.argv as
    | [string, string, string]
    | [string, string];
  const puzzle = fullPath.split('/').slice(-2).join('/');
  const [day, part] = puzzle
    .split('/')
    .map((x, i) => (i === 0 ? +x.split('-')[1] : x)) as [number, 'a' | 'b'];
  const fileName = createFileName(day, part, dataSet);
  let data: string[] | Buffer;
  if (options?.rawInput) {
    data = await readFile(fileName);
    return data;
  } else {
    data = (await readFile(fileName)).toString().split('\n');
  }
  return data;
}

function createFileName(day: number, part: 'a' | 'b', dataSet?: string) {
  return join(`day-${day}`, `${part}.data${dataSet ? `.${dataSet}` : ''}.txt`);
}

Usage example

export async function day3a(data: Buffer) {
  const input = data?.toString();
  const operationTokens = input?.split(/(?=mul\(|do\(\)|don't\(\))/);
  const partOneTotal = calculateTotal(operationTokens, false);

  return partOneTotal;
}

await runSolution(day3a, { rawInput: true });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant