Skip to content

Instantly share code, notes, and snippets.

@rumpl
Last active December 15, 2015 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rumpl/5247079 to your computer and use it in GitHub Desktop.
Save rumpl/5247079 to your computer and use it in GitHub Desktop.
Brainfuck interpreter in JavaScript
var fs = require('fs');
var Brainfuck = function () {
};
Brainfuck.prototype.init = function() {
this.data = new Array(30000);
for(var i = 0; i < this.data.length; i++) {
this.data[i] = 0;
}
this.dataPointer = 0;
this.instructionPointer = 0;
};
Brainfuck.prototype.run = function(code) {
this.init();
while (this.instructionPointer < code.length) {
switch(code[this.instructionPointer]) {
case '>':
this.dataPointer++;
break;
case '<':
this.dataPointer--;
break;
case '+':
this.data[this.dataPointer]++;
break;
case '-':
this.data[this.dataPointer]--;
break;
case '.':
process.stdout.write(String.fromCharCode(this.data[this.dataPointer]));
break;
case ',':
var response = fs.readSync(process.stdin.fd, 100, 0, "utf8");
this.data[this.dataPointer] = response[0].charCodeAt(0);
break;
case '[':
if (this.data[this.dataPointer] === 0) {
this.instructionPointer = this.findMatching(code, ']', '[', 1);
}
break;
case ']':
if(this.data[this.dataPointer] !== 0) {
this.instructionPointer = this.findMatching(code, '[', ']', -1);
}
break;
default:
throw new Error("Unknown opcode " + code[this.instructionPointer]);
}
this.instructionPointer++;
}
};
Brainfuck.prototype.findMatching = function(code, a, b, increment) {
var skip = 0;
for(var i = this.instructionPointer + increment; i < code.length; i += increment) {
if (code[i] === b) {
skip++;
} else if (code[i] === a && skip === 0) {
return i;
} else if(code[i] === a) {
skip--;
}
}
return i;
};
var br = new Brainfuck();
// Hello World
br.run('++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.');
// Merry freakin' Christmas
br.run('>+++++++[<+++++++++++>-]<.>++++[<++++++>-]<.>+++[<++++>-]<+..+++++++.>++++++++[<----------->-]<-.>+++++++[<++++++++++>-]<.>++[<++++++>-]<.>++[<------>-]<-.----.>+++++[<++>-]<.--.+++++.>+++++++[<---------->-]<-.-------.>+++++++[<+++++>-]<.>++++++++[<++++>-]<+++++.>++[<+++++>-]<.>+++[<--->-]<.>++[<+++++>-]<.+.>++[<---->-]<+.>+++[<---->-]<.>+++[<++++++>-]<.');
// ROT13
br.run('-,+[-[>>++++[>++++++++<-]<+<-[>+>+>-[>>>]<[[>+<-]>>+>]<<<<<-]]>>>[-]+>--[-[<->+++[-]]]<[++++++++++++<[>-[>+>>]>[+[<+>-]>+>>]<<<<<-]>>[<+>-]>[-[-<<[-]>>]<<[<<->>-]>>]<<[<<+>>-]]<[-]<.[-]<-,+]');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment