-
Notifications
You must be signed in to change notification settings - Fork 0
/
02.js
36 lines (24 loc) · 1.05 KB
/
02.js
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
import {open} from "fs/promises";
const inputFileHandle = await open("./data/02.txt");
const inputDataString = await inputFileHandle.readFile({encoding: "utf-8"});
await inputFileHandle.close();
const commands = inputDataString.split("\r\n");
const initialPosition = {
horizontal: 0,
depth: 0,
aim: 0
};
const { horizontal: totalHorizontal, depth: totalDepth} = commands.reduce(({horizontal, depth, aim}, currentCommand) => {
const [commandType, commandValue] = parseCommand(currentCommand);
switch (commandType) {
case "forward": return { horizontal: horizontal + commandValue, depth: depth + aim * commandValue, aim };
case "up": return { horizontal, depth, aim: aim - commandValue};
case "down": return { horizontal, depth, aim: aim + commandValue};
default: return { horizontal, depth, aim };
}
}, initialPosition);
console.log("Result: ", totalHorizontal * totalDepth);
function parseCommand(commandString) {
const [commandType, commandValueString] = commandString.split(" ");
return [commandType, parseInt(commandValueString)];
}