Skip to content

Instantly share code, notes, and snippets.

@DanielRapp

DanielRapp/bf.js Secret

Created February 23, 2012 13:52
Show Gist options
  • Save DanielRapp/4eecbc79053032a5d9eb to your computer and use it in GitHub Desktop.
Save DanielRapp/4eecbc79053032a5d9eb to your computer and use it in GitHub Desktop.
More readable brainfuck interpreter
/*
a = pointer array
p = pointer index
j = input character index
argv[3] = input string
argv[2] = code string
k = code character index
c = code character value
l = loop nesting array / stack
c=='[' && foo()
is essentially an alias to:
if (c=='[') foo()
Characters will not be evaluated if the inner-most / current ( l[0] ) loop stack value equals -1.
*/
with( process ) {
for( a=[k=j=p=0], l=[]; c=argv[2][k]; k++) {
c=='[' && l.unshift( a[p] && l[0] != -1 ? k : -1 )
c==']' && ( a[p] && l[0] >= 0 ? k = l[0] : l.splice(0, 1) )
if ( l[0] != -1 ) {
p += c=='>' ? 1 : c=='<' && -1
s = c=='+' ? 1 : c=='-' && -1
a[p] = a[p]==undefined ? s : a[p]+s
c=='.' && stdout.write(String.fromCharCode( a[p] ))
c==',' && ( a[p] = argv[3].charCodeAt(j++) )
}
}
}
@DanielRapp
Copy link
Author

A log of all variables for a Hello World program:
https://gist.github.com/a55f83942dffd6eb8c84

Nested loops:
https://gist.github.com/ea595aac86357752ff52

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment