Skip to content

Instantly share code, notes, and snippets.

@hiimjustin000
Created December 21, 2023 02:51
Show Gist options
  • Save hiimjustin000/fd30224017eb11da401e7727cd2b00a0 to your computer and use it in GitHub Desktop.
Save hiimjustin000/fd30224017eb11da401e7727cd2b00a0 to your computer and use it in GitHub Desktop.
const fs = require("fs");
const path = require("path");
const input = fs.readFileSync(path.resolve(__dirname, "input.txt"), "utf8").split("\n\n").map(x => x.split("\n"));
const workflows = {};
const parts = input[1].map(x => ({ ...JSON.parse(x.replace("{", "{\"").replace(/=/g, "\":").replace(/,/g, ",\"")), accepted: false }));
let result = 0;
for (const line of input[0]) {
const [workflow, funcs] = line.slice(0, -1).split("{").map((x, i) => i == 1 ? x.split(",") : x);
let functionString = "";
for (const func of funcs) {
if (func.includes(">")) {
const [greater, than] = func.split(">").map((x, i) => i == 1 ? x.split(":")[0] : x);
functionString += `if (part.${greater} > ${than}) return`;
const then = func.split(":")[1];
switch (then) {
case "A":
functionString += " part.accepted = true;\n";
break;
case "R":
functionString += ";\n";
break;
default:
functionString += ` workflows.${then}(part);\n`;
break;
}
}
else if (func.includes("<")) {
const [less, than] = func.split("<").map((x, i) => i == 1 ? x.split(":")[0] : x);
functionString += `if (part.${less} < ${than}) return`;
const then = func.split(":")[1];
switch (then) {
case "A":
functionString += " part.accepted = true;\n";
break;
case "R":
functionString += ";\n";
break;
default:
functionString += ` workflows.${then}(part);\n`;
break;
}
}
else {
if (func == "A") functionString += "return part.accepted = true;";
else if (func == "R") functionString += "return;";
else functionString += `return workflows.${func}(part);`;
}
}
// How do you make functions use the same scope as the parent function?
workflows[workflow] = new Function("part", functionString);
}
for (const part of parts) {
workflows.in(part);
if (part.accepted) result += part.x + part.m + part.a + part.s;
}
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment