Created
April 2, 2015 03:38
-
-
Save HakurouKen/2675dff5feee0f3485d2 to your computer and use it in GitHub Desktop.
A simple BrainFuck Javascript 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
var BrainFuck = (function(){ | |
function getBracketsPair(code){ | |
var stack = [], | |
bracket = [], | |
start, | |
i,l; | |
for (i = 0, l = code.length; i < l; i++ ) { | |
if (code[i] === '[') { | |
stack.push(i); | |
} else if (code[i] === ']') { | |
start = stack.pop(); | |
if( start ){ | |
bracket.push({ | |
start: start, | |
end: i | |
}); | |
} else { | |
throw new Error("Unpaired bracket"); | |
} | |
} | |
} | |
if (stack.length) { | |
throw new Error("Unpaired bracket"); | |
} | |
return bracket; | |
} | |
function type(o){ | |
return Object.prototype.toString.call(o).toLowerCase().slice(8,-1) | |
} | |
function exec(code,input_str){ | |
var input = type(input_str) === 'string' ? input_str.split("") : input_str, // input array | |
output = [], // output array | |
ptr = 0, // memory pointer | |
c_ptr = 0, // code ptr | |
bracket = getBracketsPair(code), // bracket pairs | |
memory = [0], // memory array | |
l = code.length, | |
token; | |
while(c_ptr < l){ | |
token = code[c_ptr]; | |
switch(token){ | |
case '+': | |
memory[ptr]++; | |
break; | |
case '-': | |
memory[ptr]--; | |
break; | |
case '<': | |
if (--ptr < 0){ | |
ptr = 0; | |
memory.unshift(0); | |
} | |
break; | |
case '>': | |
if (memory[++ptr] === undefined) { | |
memory.push(0); | |
} | |
break; | |
case ',': | |
try { | |
memory[ptr] = input.shift().charCodeAt(0); | |
} catch (e) { | |
throw Error("Wrong input"); | |
} | |
break; | |
case '.': | |
output.push(memory[ptr]); | |
break; | |
case '[': | |
if (memory[ptr] === 0) { | |
c_ptr = bracket.filter(function(b){ | |
return b.start === c_ptr | |
})[0].end - 1; | |
} | |
break; | |
case ']': | |
if (memory[ptr]) { | |
c_ptr = bracket.filter(function(b){ | |
return b.end === c_ptr | |
})[0].start - 1; | |
} | |
break; | |
default: | |
break; | |
} | |
c_ptr++; | |
} | |
return output.map(function(w){ | |
return String.fromCharCode(w); | |
}).join(""); | |
} | |
return exec; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment