-
Notifications
You must be signed in to change notification settings - Fork 0
/
BrainfuckInterpreter.js
107 lines (94 loc) · 2.64 KB
/
BrainfuckInterpreter.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
Array.prototype.peek = function() {
return this[this.length - 1];
};
const initialBandLength = 50;
class BrainfuckInterpreter {
constructor(input) {
this.input = input;
this.stdin = "";
this.band = this.emptyArray();
this.sourcecodeCursor = 0;
this.bandCursor = 0;
this.whileStack = [];
}
execute() {
let char = this.nextChar();
while(char != '\0') {
if(this.whileStack.peek() != -1) {
switch(char){
case '>':
this.incrementCursor();
break;
case '<':
this.decrementCursor();
break;
case '+':
this.band[this.bandCursor]++;
break;
case '-':
this.band[this.bandCursor]--;
break;
case '.':
this.printCurrent();
break;
case ',':
this.readInput();
break;
}
}
switch(char) {
case '[':
this.beginWhile();
break;
case ']':
this.endWhile();
break;
}
char = this.nextChar();
}
}
beginWhile() {
if(this.whileStack.peek() < 0 || this.band[this.bandCursor] == 0) {
this.whileStack.push(-1);
} else {
this.whileStack.push(this.sourcecodeCursor - 1);
}
}
endWhile() {
let cursor = this.whileStack.pop();
if(cursor != -1) {
this.sourcecodeCursor = cursor;
}
}
printCurrent() {
let chr = String.fromCharCode(this.band[this.bandCursor]);
console.log(chr);
}
readInput() {
// TODO
}
incrementCursor() {
this.bandCursor++;
if(this.bandCursor >= this.band.length) {
this.band = this.band.concat(emptyArray);
}
}
decrementCursor() {
this.bandCursor--;
if(this.bandCursor < 0) {
this.band = emptyArray().concat(this.band);
this.bandCursor += initialBandLength;
}
}
emptyArray() {
return new Array(initialBandLength).fill(0);
}
nextChar() {
if(this.sourcecodeCursor >= this.input.length) {
return '\0';
}
let char = this.input[this.sourcecodeCursor];
this.sourcecodeCursor++;
return char;
}
}