Skip to content

Instantly share code, notes, and snippets.

@zspecza
Created December 13, 2013 02:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zspecza/7938993 to your computer and use it in GitHub Desktop.
Save zspecza/7938993 to your computer and use it in GitHub Desktop.
Brainf*ck Interpreter
###
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