Created
June 4, 2013 02:40
-
-
Save cobrajs/5703206 to your computer and use it in GitHub Desktop.
RegEx-based JS Brainf*ck Interpreter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE HTML> | |
<html> | |
<head> | |
<title>BF REGEX</title> | |
<style type="text/css"> | |
textarea#src { width: 400px; height: 300px; } | |
</style> | |
</head> | |
<body> | |
<textarea id="src"></textarea> | |
<table> | |
<tr> | |
<th>Input</th> | |
<td><input id="input" /></td> | |
</tr> | |
<tr> | |
<th>Output</th> | |
<td><div id="output"></div></td> | |
</tr> | |
</table> | |
<button type="button" onclick="run()">Run</button> | |
<script> | |
var elems = (function() { | |
var elems = document.querySelectorAll("[id]"); | |
var temp = {}; | |
for (var i = 0; i < elems.length; i++) { | |
temp[elems[i].id] = elems[i]; | |
} | |
return temp; | |
})(); | |
function run() { | |
elems.output.innerHTML = ''; | |
var parseIt, parseLoop; // Declare functions | |
var src = elems.src.value; | |
var s = []; | |
var pos = 0; | |
var ipos = 0; | |
for (var i = 0; i < 10000; s[i++] = 0); | |
parseIt = function(str) { | |
var h = {}; | |
str.replace( | |
/([+-])|([<>])|(\.)|(,)|(\[)/g, | |
function(match, a, b, c, d, p) { | |
if(a){s[pos]+=a=='+'?1:-1;} | |
if(b){pos+=b=='>'?1:-1;} | |
if(c){elems.output.innerHTML+=String.fromCharCode(s[pos]);} | |
if(d){s[pos]=elems.input.value.charCodeAt(ipos++);} | |
if(e){ | |
if(!h[p]){ | |
var t = ''; | |
for (var st = p + 1, ct = 0; st < str.length && ct >= 0; st++) { | |
h[st] = 1; | |
t += str[st]; | |
if (str[st] == '[') { | |
ct++; | |
} else if (str[st] == ']') { | |
ct--; | |
} | |
} | |
t = t.slice(0, temp.length - 1); | |
if (t) { | |
parseLoop(t); | |
} | |
} | |
} | |
}); | |
}; | |
parseLoop = function(str) { | |
var breakout = 10000; | |
while(s[pos] && breakout--) { | |
parseIt(str); | |
} | |
if (!breakout) { | |
throw "Infinite loop detected"; | |
} | |
}; | |
parseIt(src); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment