-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (75 loc) · 2.67 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
const {
readFileSync
} = require("fs");
const interpret = async (filename) => {
if (!filename.endsWith('.bf')) return console.warn('Filename must end with .bf');
const filepath = `${require.main.path}\\bf\\${filename}`;
const data = readFileSync(filepath, 'utf-8');
if (!data) return console.warn('File not found');
const allowed = ['>', '<', '+', '-', '.', ',', '[', ']'];
const code = data.split('');
let cells = [0];
let thisCell = 0;
let loops = [0];
let output = '';
let looping = false;
for (let i = 0; i < code.length; i++) {
if (looping) {
if (code[i] === '[') loops++
if (code[i] === ']') {
if (loops == 0) looping = false
else loops--
}
}
if (allowed.includes(code[i])) {
switch (code[i]) {
case ">":
thisCell++
if (!cells[thisCell]) cells.push(0)
break
case "<":
thisCell--
if (thisCell < 0) {
beginning();
return 'Error: You can\'t go back with "<" before the first cell.'
}
break
case "+":
cells[thisCell]++
if (cells[thisCell] > 255) {
beginning();
return 'Cells can\'t have a value higher value than 255'
}
break
case "-":
cells[thisCell]--
break
case ".":
output = output + String.fromCharCode(cells[thisCell])
break
case ",":
cells[thisCell] = prompt().charCodeAt(1);
break;
case "[":
if (cells[thisCell] == 0) {
looping = true
} else {
loops.push(i);
}
break
case "]":
if (cells[thisCell] != 0) {
i = loops[loops.length - 1]
} else {
loops.pop()
}
}
}
function beginning() {
thisCell = 0
cells = [0]
}
}
return output
}
module.exports = interpret