Created
December 13, 2013 02:27
-
-
Save zspecza/7938993 to your computer and use it in GitHub Desktop.
Brainf*ck 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
### | |
brainfuck() function | |
description: takes a string of Brainfuck code and returns the parsed result | |
usage: brainfuck('++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.') | |
// output: 'Hello World.' | |
### | |
brainfuck = (code) -> | |
inp = '23\n' | |
out = '' | |
codeSize = code.length | |
i = 0 | |
ip = 0 | |
cp = 0 | |
dp = 0 | |
m = {} | |
loopIn = {} | |
loopOut = {} | |
tmp = [] | |
cp = 0 | |
while cp < codeSize | |
if code[cp] is '[' then tmp.push cp | |
else loopOut[loopIn[cp] = tmp.pop()] = cp if code[cp] is ']' | |
cp++ | |
cp = 0 | |
while cp < codeSize and i < 100000 | |
switch code[cp] | |
when '>' then dp++ | |
when '<' then dp-- | |
when '+' then m[dp] = ((m[dp] or 0) + 1) & 255 | |
when '-' then m[dp] = ((m[dp] or 0) - 1) & 255 | |
when '.' then out += String.fromCharCode(m[dp]) | |
when ',' then m[dp] = inp.charCodeAt(ip++) or 0 | |
when '[' then m[dp] or (cp = loopOut[cp]) | |
when ']' then cp = loopIn[cp] - 1 | |
cp++ | |
i++ | |
return out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment