Skip to content

Instantly share code, notes, and snippets.

@CitizenOfRome
Last active December 28, 2015 10:49
Show Gist options
  • Save CitizenOfRome/7488834 to your computer and use it in GitHub Desktop.
Save CitizenOfRome/7488834 to your computer and use it in GitHub Desktop.
function brainLuck(code, input){
var dp = 0, output = [], value = 0, data='', ip=0, braceCount = 0;
for(var i=0, l= code.length; i < l; i++) {
switch(code[i]){
case '>':
dp++;
if(dp >= data.length) {
data += String.fromCharCode(0);
}
break;
case '<':
dp--;
if(dp < 0) {
data = String.fromCharCode(0) + data;
dp = 0;
}
break;
case '+':
value = (data.charCodeAt(dp)||0) + 1;
if(value>255) value = 0;
data = data.substr(0,dp) + String.fromCharCode(value) + data.substr(dp+1);
break;
case '-':
value = (data.charCodeAt(dp)||0) - 1;
if(value<0) value = 255;
data = data.substr(0,dp) + String.fromCharCode(value) + data.substr(dp+1);
break;
case '.':
output.push(data[dp]);
break;
case ',':
data = data.substr(0,dp) + String.fromCharCode(input.charCodeAt(ip++)||0) + data.substr(dp+1);
break;
case '[':
value = data.charCodeAt(dp);
if(!value){
braceCount = 1;
i++;
while(i<l && braceCount>0) {
if(code[i]==='[') braceCount++;
if(code[i]===']') braceCount--;
i++;
}
}
break;
case ']':
value = data.charCodeAt(dp);
if(value){
braceCount = 1;
i--;
while(i>=0 && braceCount>0) {
if(code[i]==='[') braceCount--;
if(code[i]===']') braceCount++;
i--;
}
}
break;
}
}
return output.join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment