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
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.
https://codegolf.stackexchange.com/a/231435