-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
93 lines (77 loc) · 2.04 KB
/
index.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env node
const fs = require('fs');
// if no input provided, executes hello world brainfuck program
let input = '+[-[<<[+[--->]-[<<<]]]>>>-]>-.---.>..>.<<<<-.<+.>>>>>.>.<<.<-.';
let output = '';
let out = 'now';
let last = '';
process.argv.forEach((val, index) => {
if (index > 1) {
if (val === '-i' || val === '-o') {
last = val;
}
else if (last === '-i') {
input = fs.readFileSync(process.cwd() + '/' + val, 'utf-8');
}
else if (last === '-o') {
out = val;
}
}
});
if (input.includes(',')) {
output = 'let prompt = require(\'prompt-sync\')(); ';
}
output += 'let pointer = 0; let memory = {}; ';
// check new & init zero
const check = 'memory[pointer] === undefined && (memory[pointer] = 0); ';
// op >
const OP1 = '++pointer; ';
// op <
const OP2 = '--pointer; ';
// op +
const OP3 = check + '++memory[pointer]; memory[pointer] > 255 && (memory[pointer] = 0); ';
// op -
const OP4 = check + '--memory[pointer]; memory[pointer] < 0 && (memory[pointer] = 255); ';
// op .
const OP5 = 'process.stdout.write(String.fromCharCode(memory[pointer])); ';
// op ,
const OP6 = 'console.log(); memory[pointer] = prompt(\'Please type one more character: \', \'0\').charCodeAt(0);';
// op [
const OP7 = 'while (memory[pointer]) { ';
// op ]
const OP8 = ' }';
for (let i = 0; i < input.length; i++) {
switch (input[i]) {
case '>':
output += OP1;
break;
case '<':
output += OP2;
break;
case '+':
output += OP3;
break;
case '-':
output += OP4;
break;
case '.':
output += OP5;
break;
case ',':
output += OP6;
break;
case '[':
output += OP7;
break;
case ']':
output += OP8;
break;
default:
}
}
if (out === 'now') {
eval(output);
}
else {
fs.writeFileSync(process.cwd() + '/' + out, output, 'utf-8');
}