Created
May 10, 2017 02:51
-
-
Save Sait2000/2148a6d02f4334d3a5554455e03aa402 to your computer and use it in GitHub Desktop.
bf interpreter in js
This file contains hidden or 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
| (function () { | |
| function bf(code, input) { | |
| const loop_mapping = new Map | |
| const code_points = [...code] | |
| const input_code_points = [...input].reverse().map(c => c.codePointAt()) | |
| let res = '' | |
| { | |
| const loop_open_stack = [] | |
| for (const i_c of code_points.entries()) { | |
| const i = i_c[0] | |
| const c = i_c[1] | |
| if (c === '[') { | |
| loop_open_stack.push(i) | |
| } else if (c === ']') { | |
| if (loop_open_stack.length) { | |
| const j = loop_open_stack.pop() | |
| loop_mapping.set(i, j) | |
| loop_mapping.set(j, i) | |
| } | |
| } | |
| } | |
| } | |
| { | |
| const left = [] | |
| const right = [] | |
| let current = 0 | |
| for (let i = 0; i < code_points.length; i++) { | |
| const c = code_points[i] | |
| if (c === '+') { | |
| current++ | |
| } else if (c === '-') { | |
| current-- | |
| } else if (c === '<') { | |
| if (!left.length) { | |
| left.push(0) | |
| } | |
| right.push(current) | |
| current = left.pop() | |
| } else if (c === '>') { | |
| if (!right.length) { | |
| right.push(0) | |
| } | |
| left.push(current) | |
| current = right.pop() | |
| } else if (c === '[') { | |
| if (!current) { | |
| i = loop_mapping.get(i) | |
| } | |
| } else if (c === ']') { | |
| if (current) { | |
| i = loop_mapping.get(i) | |
| } | |
| } else if (c === '.') { | |
| res += String.fromCodePoint(current) | |
| } else if (c === ',') { | |
| if (input_code_points.length) { | |
| current = input_code_points.pop() | |
| } else { | |
| current = -1 | |
| } | |
| } | |
| current = ((current % 256) + 256) % 256 | |
| } | |
| } | |
| return res | |
| } | |
| console.log(bf('++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.', '')) | |
| })(); |
This file contains hidden or 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
| console.log("Hello World!\n"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment