Skip to content

Instantly share code, notes, and snippets.

@pineapplebox
Last active April 24, 2024 12:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pineapplebox/b2c1035a1786286fa26aed18882e70ca to your computer and use it in GitHub Desktop.
Save pineapplebox/b2c1035a1786286fa26aed18882e70ca to your computer and use it in GitHub Desktop.
A 158-byte JS Brainf*ck interpreter

BF.js

Summary

After realizing how bloated most available Javascript brainf*ck interpreters are, I created BF.js- what I believe to be the smallest brainf*ck interpreter built with JS (158 bytes). Please let me know if there are any possible improvements to the code, or if there are any smaller interpreters in JS.

for(a=[p=x=i=0],r="";l=s[i++];">"==l?p++:"<"==l?p--:"+"==l?a[p]++:"-"==l?a[p]--:"."==l?r+="&#"+v:","==l?a[p]=~~prompt():"["==l?x=i:"]"==l&&v>0?i=x:x)v=a[p]|=0

Interpreter with nested loop support (178 bytes):

for(x=[r=""],a=[p=i=c=0];l=s[i++];">"==l?p++:"<"==l?p--:"+"==l?a[p]++:"-"==l?a[p]--:"."==l?r+="&#"+v:","==l?a[p]=~~prompt():"["==l?x[c++]=i:"]"==l&&0<v?i=x[c---1]-1:c--)v=a[p]|=0

Usage

Using BF.js is pretty simple. Simple declare the code with var s = "%code%", at the beginning of the program.

The outputted text is stored as the variable "r". Instead of using String.fromCharCode, in order to reduce the length of the code, the output is stored as HTML ascii codes, which can be printed to the DOM. The best way to do this is with: document.body.innerHTML+=r

You may also want to use line feeds. This can be done without modification, however you will need to print the output within a pre tag like follows: document.body.innerHTML+="<pre>"+r+"</pre>"

As follows is an example of a Hello World! program:

var s = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.";
for(a=[p=x=i=0],r="";l=s[i++];">"==l?p++:"<"==l?p--:"+"==l?a[p]++:"-"==l?a[p]--:"."==l?r+="&#"+v:","==l?a[p]=~~prompt():"["==l?x=i:"]"==l&&v>0?i=x:x)v=a[p]|=0;
document.body.innerHTML+=r;

Other examples:

Thanks to u/Irratix for several significant suggestions and reductions to the program's length

Feel free to comment your examples and I'll add them here :) If you'd like to use this BF.js's source, please provide credit.

@d-s-x
Copy link

d-s-x commented Jan 5, 2022

Please let me know if there are any possible improvements to the code, or if there are any smaller interpreters in JS.

https://codegolf.stackexchange.com/a/231435

@hyperknf
Copy link

doesnt work on node.js since prompt()

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