aboutsummaryrefslogtreecommitdiff
path: root/2022/21-Monkey-Math/first.js
blob: b6da414425a58e27a35dd1818fd5f65a66e90ea1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import * as fs from "fs";

const simple = /(\w+): (\d+)/;
const operation = /(\w+): (\w+) ([+\-*/]) (\w+)/;

function load(filename) {
	let res = {};
	fs.readFileSync(filename, "utf8")
		.trim()
		.split("\n")
		.forEach(line => {
			const s = line.match(simple);
			if (s) {
				res[s[1]] = function() { return parseInt(s[2]); };
			} else {
				const o = line.match(operation);
				res[o[1]] = function () {
					let left = res[o[2]]();
					let right = res[o[4]]();
					switch(o[3]) {
					case "+": return left + right;
					case "-": return left - right;
					case "*": return left * right;
					case "/": return left / right;
					}
				};
			}
		});
	return res;
}

let example = load("example");
let input = load("input");

function solve(input) {
	return input["root"]();
}

const exampleOutput = solve(example);
if (exampleOutput !== 152) {
	console.log("Example failed with " + exampleOutput);
	process.exit(1); // eslint-disable-line
}

console.log(solve(input));