Skip to content

Instantly share code, notes, and snippets.

@ijse
Created September 14, 2016 11: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 ijse/eb95ab1985f79fe0cb728ac21077c906 to your computer and use it in GitHub Desktop.
Save ijse/eb95ab1985f79fe0cb728ac21077c906 to your computer and use it in GitHub Desktop.
brainfuck
// Brainfuck.
//
// codewars: https://www.codewars.com/kata/my-smallest-code-interpreter-aka-brainf-star-star-k/train/javascript
// brainfuck debug tool: http://www.iamcal.com/misc/bf_debug/
// brainfuck on wikipedia: https://zh.wikipedia.org/wiki/Brainfuck
function brainLuck(code, input){
let codeInArray = code.split('');
let inputInArray = input.split('');
console.log(code);
console.log(inputInArray);
let ptc = 0;
let ptr = 0;
let output = '';
let tape = [];
let stack = [];
let direction = 1;
let isMoving = false;
const instructions = {
'>': () => !isMoving && (ptr ++),
'<': () => !isMoving && (ptr --),
// '+': () => !isMoving && (tape[ptr] = String.fromCharCode(((tape[ptr]||'\0').charCodeAt() + 1)%256)),
'+': () => {
if(isMoving) return;
if(!tape[ptr]) {
tape[ptr] = '\0';
}
tape[ptr] = String.fromCharCode((tape[ptr].charCodeAt() + 1) % 256);
},
'-': () => !isMoving && (tape[ptr] = String.fromCharCode(((tape[ptr]||'\0').charCodeAt() - 1)%256)),
'.': () => !isMoving && (output += tape[ptr]),
',': () => !isMoving && (tape[ptr] = inputInArray.shift() || '\0'),
'[': () => {
stack.push(ptc);
if (!isMoving && tape[ptr].charCodeAt() === 0) {
isMoving = true;
}
},
']': () => {
let last = stack.pop() - 1;
if (tape[ptr].charCodeAt() !== 0) {
ptc = last;
console.log('go back ptc:', ptc);
isMoving = false;
}
}
}
while (ptc < codeInArray.length) {
let cmdName = codeInArray[ptc];
console.log('cmd: ', cmdName, tape, ptr, isMoving);
instructions[cmdName]();
ptc += 1;
console.log('output:', output);
}
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment