Skip to content

Instantly share code, notes, and snippets.

@lontivero
Last active July 12, 2016 00: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 lontivero/b50f6052fc8a35d225a552b455b8914c to your computer and use it in GitHub Desktop.
Save lontivero/b50f6052fc8a35d225a552b455b8914c to your computer and use it in GitHub Desktop.
My Brainfuck language interpreter in exactly 19 LOC
run=(code, input)->
[dptr, cptr, marks, mem, output, stack]=[0, 0, [], (0 for [1..100]), [], []]
for cmd, pos in code
if cmd is '[' then stack.push(pos)
if cmd is ']' then marks[marks[pos] = stack.pop()]=pos
while cptr < code.length
switch code[cptr]
when '+' then mem[dptr] = mem[dptr] + 1 or 1
when '-' then mem[dptr] = mem[dptr] - 1 or 0
when '>' then dptr++
when '<' then dptr--
when '[' then cptr = marks[cptr] if mem[dptr] is 0
when ']' then cptr = marks[cptr] if mem[dptr] isnt 0
when '.' then output.push(String.fromCharCode(mem[dptr]))
when ',' then c=input.shift(); mem[dptr] = c.charCodeAt(0) if c instanceof string
cptr++
output
alert run(""">++++++++++>+>+[
[+++++[>++++++++<-]>.<++++++[>--------<-]+<<<]>.>>[
[-]<[>+<-]>>[<<+>+>-]<[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-
[>+<-[>+<-[>+<-[>[-]>+>+<<<-[>+<-]]]]]]]]]]]+>>>
]<<<
]""").join('')
alert run("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.").join('')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment