-
Notifications
You must be signed in to change notification settings - Fork 0
/
brainfuck.js
63 lines (59 loc) · 1.59 KB
/
brainfuck.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
// From https://github.com/DanielBaulig/brainfuck.js
function Brainfuck(code) {
this.code = code;
this.ip = 0;
this.p = 0;
this.data = [];
this.loopstack = [];
}
Brainfuck.prototype.run = function(instructions) {
instructions = instructions || Infinity;
var nextInstruction = this.code[this.ip];
while(instructions-- && nextInstruction) {
switch(nextInstruction) {
case '+':
this.data[this.p] = (this.data[this.p] || 0) + 1;
break;
case '-':
this.data[this.p] = (this.data[this.p] || 0) - 1;
break;
case '<':
this.p--;
break;
case '>':
this.p++;
break;
case '.':
this.write(this.data[this.p] || 0);
break;
case ',':
this.data[this.p] = this.read();
break;
case '[':
var openBrackets = 1;
if (this.data[this.p]) {
this.loopstack.push(this.ip);
} else {
while (openBrackets && this.code[++this.ip]) {
if (this.code[this.ip] === ']') {
openBrackets--;
} else if (this.code[this.ip] === '[') {
openBrackets++;
}
}
}
break;
case ']':
this.ip = this.loopstack.pop() - 1;
break;
default:
if (console) console.log('Warning: invalid brainfuck instruction ' + nextInstruction);
break;
}
nextInstruction = this.code[++this.ip];
}
};
Brainfuck.prototype.read = function() {
};
Brainfuck.prototype.write = function(data) {
};