Created
February 4, 2016 15:38
-
-
Save exyi/fefe564615be2c21a2d3 to your computer and use it in GitHub Desktop.
Brainfuck in ts
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
class Bf { | |
element: HTMLElement; | |
exec(script: string, input: string, inputPos = [0], pos = 0, data: number[] = [], ptr = [0]) { | |
while (script.length > pos) { | |
switch (script[pos]) { | |
case '+': data[ptr[0]] = ((data[ptr[0]] | 0) + 1) % 256; | |
break; | |
case '-': data[ptr[0]] = ((data[ptr[0]] | 0) - 1) % 256; | |
break; | |
case '<': ptr[0]--; | |
break; | |
case '>': ptr[0]++; | |
break; | |
case '.': | |
this.element.innerText += String.fromCharCode(data[ptr[0]]); | |
break; | |
case ',': | |
if (inputPos[0] >= input.length) throw "input:"; | |
data[ptr[0]] = input.charCodeAt(inputPos[0]); | |
inputPos[0]++; | |
break; | |
case '[': | |
var p = pos + 1; | |
if (data[ptr[0]]) { | |
while (data[ptr[0]]) { | |
pos = this.exec(script, input, inputPos, p, data, ptr); | |
} | |
} | |
else { | |
var cc = 1; | |
while (cc > 0) { | |
pos++; | |
if (script[pos] == '[') cc++; | |
else if (script[pos] == ']') cc--; | |
} | |
} | |
break; | |
case ']': return pos; | |
break; | |
} | |
pos++; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment