Skip to content

Instantly share code, notes, and snippets.

@dreampuf

dreampuf/bf.js

Created Sep 3, 2011
Embed
What would you like to do?
BF runtime
(function(g) {
var cur = 0,
p = 0,
mem = [0],
ret = [],
slen = -1,
pos = [],
unlimit_loop = 5000,
tmp = "",
ptype = Object.prototype.toString,
run = function(str) {
slen = str.length;
while(cur < slen) {
tmp = str.charAt(cur);
switch(str.charAt(cur)) {
case ">":
if(p < mem.length - 1) p++;
else (p = mem.push(undefined) - 1);
break;
case "<":
if(p > 0) p--;
break;
case "+":
if(ptype.apply(mem[p]) == "[object Number]") mem[p]++;
else throw new Error("wrong data type");
break;
case "-":
if(ptype.apply(mem[p]) == "[object Number]") mem[p]--;
else throw new Error("wrong data type");
break;
case ",":
if(ptype.apply(mem[p]) != "[object Number]") mem[p] = 0;
while((tmp = str.charAt(++cur)).charAt() - 48 < 10) {
mem[p] = mem[p] * 10 + (tmp|0);
}
cur--;
break;
case ".":
if(ptype.apply(mem[p]) == "[object Number]") ret.push(mem[p]) && (mem[p] = undefined);
else throw new Error("wrong data type");
break;
case "[":
pos.push(cur);
if(unlimit_loop-- == 0) throw new Error("unlimit loop");
break;
case "]":
if(mem[p] > 0) cur = pos.pop() - 1;
else pos.pop();
break;
default:
console.log("你真调皮");
}
cur++;
}
return ret;
};
g.bf = function(str) {
cur = 0,
p = 0,
mem = [],
ret = [],
pos = [],
slen = -1, tmp="";
return run(str);
};
})(window);
//base on Qunit
module("Logic");
test("bf", function() {
deepEqual(bf(",45+>,5-<.>."), [46, 4]);
deepEqual(bf(",356."), [356]);
deepEqual(bf(",1>,2>,3>,4>,5>,6.<.<.<.<.<."), [6, 5, 4, 3, 2, 1]);
deepEqual(bf(",3>,2[<+>-]<."), [5]);
deepEqual(bf(",0>,10[>,10[>,10[<<<<+>>>-]<-]<-]<."), [1000]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment