Skip to content

Instantly share code, notes, and snippets.

@st98
Last active December 30, 2015 11:19
Show Gist options
  • Save st98/7821765 to your computer and use it in GitHub Desktop.
Save st98/7821765 to your computer and use it in GitHub Desktop.
Brainf*ckのJavaScript実装です。Cのプリプロセッサで実装したアレみたいな感じです。やはり雑。
var bfeval = function (source) {
var
code = '',
index = 0,
length = source.length,
result;
code += '(function () {';
code += 'var mem = [], ptr = 0, result = "";';
for (; index < length; index++) {
switch (source[index]) {
case '>': code += 'ptr = (ptr + 1) % 30000;'; break;
case '<': code += 'ptr = ptr - 1 < 0 ? 30000 - 1 : ptr - 1 ;'; break;
case '+': code += 'mem[ptr] = typeof mem[ptr] !== "undefined" ? (mem[ptr] + 1) % 256 : mem[ptr] = 1;'; break;
case '-': code += 'mem[ptr] = typeof mem[ptr] !== "undefined" ? (mem[ptr] - 1 < 0 ? 256 - 1 : mem[ptr] - 1) : mem[ptr] = 256 - 1;'; break;
case '.': code += 'result += String.fromCharCode(mem[ptr]);'; break;
case ',': code += 'mem[ptr] = prompt("").charCodeAt(0) % 256;'; break;
case '[': code += 'while (mem[ptr] !== 0) {'; break;
case ']': code += '}'; break;
}
}
code += 'return result;';
code += '})();';
result = eval(code);
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment