-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbrainfuck.js
94 lines (84 loc) · 2.35 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
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
// Brainfuck is the most minimalistic scripting language ever.
// Some years ago, I made an interpreter using C#. Now I'm porting it to Javascript.
// For the language specification, refer to http://esolangs.org/wiki/Brainfuck
// Maybe I'll add comments to the code below someday.
// For now, rest assured that I have tested it against some examples, from hello world and cat programs to the more complex calculators.
function brainfuck(code) {
var data = [];
data.length = 30000;
var j;
for (j = 0; j < 30000; j++) {
data[j] = 0;
}
j = 0;
var printQueue = "";
for (var i = 0; i < code.length; i++) {
if (code[i] == ">") {
j++;
if (j >= 30000) {
throw new Error("Data pointer overflow.");
}
} else if (code[i] == "<") {
j--;
if (j < 0) {
throw new Error("Data pointer underflow");
}
} else if (code[i] == "+") {
data[j]++;
if (data[j] > 255) {
data[j] = 0;
}
} else if (code[i] == "-") {
data[j]--;
if (data[j] < 0) {
data[j] = 255;
}
} else if (code[i] == ".") {
printQueue += String.fromCharCode(data[j]);
} else if (code[i] == ",") {
var input = prompt("Input a single character at position " + j + " (extra characters will be ignored).");
data[j] = input.charCodeAt(0);
} else if (code[i] == "[") {
if (data[j] == 0) {
var bracketCount = 0;
for (var k = i + 1; k < code.length; k++) {
if (code[k] == "[") {
bracketCount++;
} else if (code[k] == "]") {
bracketCount--;
}
if (bracketCount < 0) {
break;
}
}
if (k == code.length) {
throw new Error("Unmatched bracket at index " + i + ".")
} else {
i = k;
}
}
} else if (code[i] == "]") {
if (data[j] != 0) {
var bracketCount = 0;
for (var k = i - 1; k > 0; k--) {
if (code[k] == "]") {
bracketCount++;
} else if (code[k] == "[") {
bracketCount--;
}
if (bracketCount < 0) {
break;
}
}
if (k == 0) {
throw new Error("Unmatched bracket at index " + i + ".")
} else {
i = k;
}
}
}
}
if (printQueue.length > 0) {
return printQueue;
}
}