Created
September 14, 2016 11:58
-
-
Save ijse/eb95ab1985f79fe0cb728ac21077c906 to your computer and use it in GitHub Desktop.
brainfuck
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
// 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