Created
December 10, 2021 15:55
-
-
Save jprochazk/cee7b307a2bcf794c6aa7aac543f7257 to your computer and use it in GitHub Desktop.
brainfuck interpreter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Brainfuck { | |
memory = new Uint8Array(30000); | |
ptr = 0; | |
input = { read() { return 0 } }; | |
output = { write(v) { console.log(String.fromCharCode(v)) } }; | |
run(code) { | |
for (let i = 0, len = code.length; i < len; ++i) { | |
let c = code.charAt(i); | |
switch (c) { | |
// move pointer right | |
case '>': this.ptr += 1; break; | |
// move point left | |
case '<': this.ptr -= 1; break; | |
// increment cell | |
case '+': this.memory[this.ptr] += 1; break; | |
// decrement cell | |
case '-': this.memory[this.ptr] -= 1; break; | |
// write cell to output | |
case '.': this.output.write(this.memory[this.ptr]); break; | |
// read to cell from output | |
case ',': this.memory[this.ptr] = this.input.read(); break; | |
// jump to next `]` if cell is 0 | |
case '[': if (this.memory[this.ptr] === 0) { | |
while (i !== len - 1 && code.charAt(i++) !== ']'); | |
} break; | |
// jump to previous `[` if cell is not 0 | |
case ']': if (this.memory[this.ptr] !== 0) { | |
while (i !== 0 && code.charAt(--i) !== '['); | |
} break; | |
// ignore all other characters | |
default: break; | |
} | |
} | |
} | |
reset() { | |
for (let i = 0, len = this.memory.length; i < len; ++i) { | |
this.memory[i] = 0; | |
} | |
this.ptr = 0; | |
} | |
} | |
let vm = new Brainfuck; | |
vm.run(` | |
++ Cell c0 = 2 | |
> +++++ Cell c1 = 5 | |
[ Start your loops with your cell pointer on the loop counter (c1 in our case) | |
< + Add 1 to c0 | |
> - Subtract 1 from c1 | |
] End your loops with the cell pointer on the loop counter | |
At this point our program has added 5 to 2 leaving 7 in c0 and 0 in c1 | |
but we cannot output this value to the terminal since it is not ASCII encoded | |
To display the ASCII character "7" we must add 48 to the value 7 | |
We use a loop to compute 48 = 6 * 8 | |
++++ ++++ c1 = 8 and this will be our loop counter again | |
[ | |
< +++ +++ Add 6 to c0 | |
> - Subtract 1 from c1 | |
] | |
< . Print out c0 which has the value 55 which translates to "7"! | |
`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment