forked from jesus-seijas-sp/hand-challenge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.js
66 lines (54 loc) · 1.4 KB
/
solution.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const fs = require('fs');
const program = [...fs.readFileSync('input.hand', 'utf8')];
const memory = [0];
let index = 0;
let pointer = 0;
const moveToNextCell = () => {
++pointer;
if(memory[pointer] === undefined) memory.push(0);
}
const moveToPrevCell = () => {
--pointer;
}
const increaseCellValue = () => {
memory[pointer] = memory[pointer] + 1 > 255 ? 0 : memory[pointer] + 1;
}
const decreaseCellValue = () => {
memory[pointer] = memory[pointer] - 1 < 0 ? 255 : memory[pointer] - 1;
}
const startLoop = () => {
if(memory[pointer] === 0) {
let counter = 1;
while(counter !== 0) {
++index;
if(program[index] === "🤜") ++counter;
if(program[index] === "🤛") --counter;
}
}
}
const endLoop = () => {
if(memory[pointer] !== 0) {
let counter = 1;
while(counter !== 0) {
--index;
if(program[index] === "🤛") ++counter;
if(program[index] === "🤜") --counter;
}
}
}
const displayCellValue = () => {
process.stdout.write(String.fromCharCode(memory[pointer]));
}
const instructions = {
"👉": moveToNextCell,
"👈": moveToPrevCell,
"👆": increaseCellValue,
"👇": decreaseCellValue,
"🤜": startLoop,
"🤛": endLoop,
"👊": displayCellValue
}
while(index < program.length) {
instructions[program[index]]();
index++;
}