Skip to content

Instantly share code, notes, and snippets.

@simon-tiger
Created June 3, 2021 14:58
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 simon-tiger/9479da4c116b85c7a5473a847b8b5ca7 to your computer and use it in GitHub Desktop.
Save simon-tiger/9479da4c116b85c7a5473a847b8b5ca7 to your computer and use it in GitHub Desktop.
const fs = require("fs");
const code = fs.readFileSync("./program.bf", "utf8");
function run(code) {
const cells = new Uint8Array(30000);
let currentCell = 0;
let commandIdx = 0;
let output = "";
while (commandIdx < code.length) {
const command = code[commandIdx];
let increaseCommandIdx = true;
if (command === "+") {
cells[currentCell]++;
} else if (command === "-") {
cells[currentCell]--;
} else if (command === ">") {
currentCell++;
} else if (command === "<") {
currentCell--;
} else if (command === ",") {
// one character input lol
const buffer = Buffer.alloc(1);
fs.readSync(0, buffer, 0, 1);
const char = buffer.toString("utf8");
cells[currentCell] = char.charCodeAt(0);
} else if (command === ".") {
output += String.fromCharCode(cells[currentCell]);
} else if (command === "[") {
if (cells[currentCell] === 0) {
// bracket matching algorithm lol
let level = 0;
for (let i = commandIdx+1; i < code.length; i++) {
if (code[i] === "[") level++;
else if (code[i] === "]") level--;
if (level < 0) {
commandIdx = i;
increaseCommandIdx = false;
break;
}
}
}
} else if (command === "]") {
if (cells[currentCell] !== 0) {
// closing bracket matching algorithm lol
let level = 0;
for (let i = commandIdx-1; i >= 0; i--) {
if (code[i] === "]") level++;
else if (code[i] === "[") level--;
if (level < 0) {
commandIdx = i;
increaseCommandIdx = false;
break;
}
}
}
}
if (increaseCommandIdx) {
commandIdx++;
}
}
console.log(output);
}
run(code);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment