Skip to content

Instantly share code, notes, and snippets.

@MoutPessemier
Created May 1, 2023 16:13
Show Gist options
  • Save MoutPessemier/4fd8032952c3664e6e0d63377bd88b24 to your computer and use it in GitHub Desktop.
Save MoutPessemier/4fd8032952c3664e6e0d63377bd88b24 to your computer and use it in GitHub Desktop.
A small and simple Brainfck compiler function in javascript
const compile = (input) => {
const tape = new Array(10).fill(0);
let pointer = 0;
let isLooping = false;
let loopStack = [];
let innerLoops = 0;
let output = "";
for (let i = 0; i < input.length; i++) {
const c = input[i];
if (isLooping) {
if (c === "[") innerLoops++;
if (c === "]") {
if (innerLoops === 0) isLooping = false;
else innerLoops--;
}
continue;
}
switch (c) {
case "+":
tape[pointer]++;
break;
case "-":
tape[pointer]--;
break;
case ",":
tape[pointer] = prompt()[0].charCodeAt();
break;
case ".":
output += String.fromCharCode(tape[pointer]);
break;
case "<":
pointer--;
tape[pointer] = tape[pointer] || 0;
break;
case ">":
pointer++;
tape[pointer] = tape[pointer] || 0;
break;
case "[":
tape[pointer] === 0 ? (isLooping = true) : loopStack.push(i);
break;
case "]":
tape[pointer] !== 0
? (i = loopStack[loopStack.length - 1])
: loopStack.pop();
break;
}
}
console.log(output);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment