I wrote a Brainfuck interpreter in JavaScript, however it is quite buggy and I can't figure out what I'm doing wrong. It works for programs I've written, but fails on most programs I find on the internet. It seems that the while loop doesn't work correctly when it is supposed to skip over. When debugging, the value of i
(index) behaves as I intended. In addition, I feel that my code is overly complicated for such a simple task, and I think there might be a way to simplify my code, although I can't think of a way :(
Here is the code:
function execBrainf() {
document.getElementById("output").value = "";
var ptr = 0, i, ii;
var cells = new Array(), labels = new Array();
for (i = 0; i < 30000; ++i)
cells[i] = 0;
for (i = ii = 0; i < document.getElementById("code").value.length; ++i) {
switch (document.getElementById("code").value.charAt(i)) {
case '>':
++ptr; break;
case '<':
--ptr; break;
case '+':
cells[ptr] = (++cells[ptr] % 256); break;
case '-':
cells[ptr] = (--cells[ptr] % 256); break;
case ',':
cells[ptr] = (ii > document.getElementById("input").length ? 0 : document.getElementById("input").value.charCodeAt(ii++)); break;
case '.':
document.getElementById("output").value = document.getElementById("output").value + String.fromCharCode(cells[ptr]); break;
case '[':
(cells[ptr] == 0 ? i = document.getElementById("code").value.indexLoopEnd(i) : labels.push(i)); break;
case ']':
(cells[ptr] == 0 ? labels.pop() : i = labels[labels.length - 1]); break;
}
}
}
function indexLoopEnd(i) {
var x = 1;
while (x > 0) {
switch (this.charAt(++i)) {
case '[':
++x; break;
case ']':
--x; break;
}
}
return i;
}
I am using the html here: http://esotools.ml/brainfuck/interpreter.html
I am looking for:
- what the problem is
- suggestions on making the code prettier
- suggestions for improving the algorithm
I am not too concerned about optimization yet, and would like to focus on these three things.