Brainfuck interpreter in javascript
I got bored today and decided to make a brainfuck interpreter with javascript. After I was done I did a quick google search to see what other people did for a js solution to compare and constrast however I couldn't find anything with less than 100 lines (to be fair others had more features such as step debugging and config options).
So here I present my rather naive (but small) version in 17 lines of javascript, 328 bytes manually minified.
So here I present my rather naive (but small) version in 17 lines of javascript, 328 bytes manually minified.
function bf(code, input){ var src = "var ptr = 0, inptr = 0, output = '', data = new Uint8Array(30000);", op = { '>': '++ptr;', '<': '--ptr;', '+': '++data[ptr];', '-': '--data[ptr];', '.': 'output += String.fromCharCode(data[ptr]);', ',': 'data[ptr] = input.charCodeAt(inptr++)||0;', '[': 'while(data[ptr]){', ']': '}' }; code.split('').map(function(c){ src += op[c] || ''; }); return (new Function('input', src + 'return output;')).call(0, typeof input == 'string' ? input : ''); }...and some samples...
// hello world bf('++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.') // echo input bf(',[.,]', 'input') // echo reverse input bf(',[>,]<[.<]', 'input')Here's a link to a live sample.
Comments
Post a Comment