Skip to content

Instantly share code, notes, and snippets.

@amasad
Created May 30, 2012 08:51
Show Gist options
  • Save amasad/2834677 to your computer and use it in GitHub Desktop.
Save amasad/2834677 to your computer and use it in GitHub Desktop.
function bf (code) {
var codeSize = code.length;
var cp = 0, dp = 0, m = {};
var loopIn = {}
, loopOut = {}
, tmp = [];
for (cp = 0; cp < codeSize ; cp++)
if (code[cp] == '[') tmp.push(cp);
else if (code[cp] == ']') loopOut[loopIn[cp] = tmp.pop()] = cp;
var ops = {
'>': function () { dp++; return runNext;}
, '<': function () { dp--; return runNext;}
, '+': function () {m[dp] = ((m[dp]||0)+1)&255; return runNext;}
, '-': function () {m[dp] = ((m[dp]||0)-1)&255; return runNext;}
, '.': function () {console.log(String.fromCharCode(m[dp])); return runNext;}
, ',': function () {
return function () {
console.input(function (data) {
m[dp] = data.charCodeAt(0) || 0;
run(runNext);
});
};
}
, '[': function () {m[dp]||(cp=loopOut[cp]); return runNext;}
, ']': function () {cp = loopIn[cp]-1; return runNext;}
};
function noop () {}
function runNext () {
cp++;
if (cp < codeSize)
return (ops[code[cp]] || noop)();
}
function run (cont) {
while (typeof cont === 'function') {
cont = cont();
}
}
cp = -1;
run(runNext);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment