Skip to content

Instantly share code, notes, and snippets.

@KCreate
Created May 18, 2017 09:20
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 KCreate/fdf818f0d80872ce9852f586b6145055 to your computer and use it in GitHub Desktop.
Save KCreate/fdf818f0d80872ce9852f586b6145055 to your computer and use it in GitHub Desktop.
Brainfuck interpreter written in Javascript
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
body * {
margin: 10px;
padding: 0;
display: block;
box-sizing: border-box;
}
</style>
</head>
<body>
<textarea id="input" rows="8" cols="80"></textarea>
<textarea id="stdinput" rows="8" cols="80"></textarea>
<button type="button" name="execute" id="execute">Execute</button>
<textarea id="output" rows="8" cols="80"></textarea>
<script charset="utf-8">
const input = document.getElementById("input");
const stdinput = document.getElementById("stdinput");
const output = document.getElementById("output");
const execute = document.getElementById("execute");
execute.onclick = () => {
output.value = "";
const program = input.value.split("");
const stdin = stdinput.value.split("");
const runner = new Brainfuck(program, () => {
return (stdin.shift() || "0").charCodeAt(0);
}, (byte) => {
output.value += byte;
});
runner.execute();
}
class Brainfuck {
constructor(program, stdin, stdout) {
this.program = program;
this.stdin = stdin;
this.stdout = stdout;
this.cells = new Array(30000).fill(0); // memory cells
this.ptr = 0; // memory pointer
this.pc = 0; // program counter
}
/*
Begin executing the program
*/
execute() {
// Execute while we're at a legal position
while (this.pc >= 0 && this.pc < this.program.length) {
const op = this.program[this.pc];
switch (op) {
case ">": {
this.ptr++;
break;
}
case "<": {
this.ptr--;
break;
}
case "+": {
this.cells[this.ptr]++;
break;
}
case "-": {
this.cells[this.ptr]--;
break;
}
case ".":
this.stdout(String.fromCharCode(this.cells[this.ptr]));
break;
case ",":
let input = this.stdin();
this.cells[this.ptr] = input;
break;
case "[":
case "]":
case " ": break;
case "\n": break;
case "\r": break;
default:
this.stdout("Error: Unexpected char: " + op);
this.pc = -2;
}
// Increment the program counter
this.pc++;
}
}
}
</script>
</body>
</html>
@KCreate
Copy link
Author

KCreate commented May 18, 2017

Still missing loops

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment