Skip to content

Instantly share code, notes, and snippets.

@maxpert maxpert/Brainfuck.js
Last active Dec 21, 2017

Embed
What would you like to do?
Minimal BrainF*ck implementation in JS

JS Brainfuck

Primary reasons of this implementation is:

  • Better readability
  • Minimal implementation
  • Single function implementation with iterative approach
  • Compressable to small size (under 350 bytes)

Demo

/**
* Copyright 2017 Zohaib Sibte Hassan
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// fmb = F**K My Brain
// ins = instructions string
// oup = terminal output callback function
// inp = terminal input callback function
function fmb(ins, oup, inp) {
var m = [], dp = 0, ip = 0,
il = ins.length, scp = {},
op, mdp;
for(; ip < il; ip++) {
op = ins[ip];
if (op == '[') m.push(ip);
if (op == ']') {
scp[ip] = m.pop();
scp[scp[ip]] = ip + 1;
}
}
for(ip = 0, m = []; ip < il;) {
op = ins[ip];
dp += (op == '>' && 1) || (op == '<' && -1) || 0;
mdp = m[dp];
mdp = (op == ',' && inp && inp()) ||
(mdp == 128 && -128) ||
(mdp == -129 && 127) ||
mdp || 0;
mdp += (op == '+' && 1) || (op == '-' && -1) || 0;
ip = (op == '[' && !mdp && scp[ip]) ||
(op == ']' && scp[ip]) ||
(ip + 1);
if (op == '.' && oup) oup(mdp);
m[dp] = mdp;
}
return [m, dp];
}
function fmb(r,f,n){for(var o,p,t=[],u=0,e=0,h=r.length,a={};e<h;e++)"["==(o=r[e])&&t.push(e),"]"==o&&(a[e]=t.pop(),a[a[e]]=e+1);for(e=0,t=[];e<h;)p=t[u+=(">"==(o=r[e])?1:"<"==o&&-1)||0],p=","==o&&n&&n()||128==p&&-128||-129==p&&127||p||0,p+=("+"==o?1:"-"==o&&-1)||0,e="["==o&&!p&&a[e]||"]"==o&&a[e]||e+1,"."==o&&f&&f(p),t[u]=p;return[t,u]}
var code = '-[------->+<]>-.-[->+++++<]>++.+++++++..+++.[--->+<]>-----.--[->++++<]>-.--------.+++.------.--------.';
var output = '';
fmb(code, function(v) {
output += String.fromCharCode(v);
});
console.log(output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.