Skip to content

Instantly share code, notes, and snippets.

@exyi
Created February 4, 2016 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save exyi/fefe564615be2c21a2d3 to your computer and use it in GitHub Desktop.
Save exyi/fefe564615be2c21a2d3 to your computer and use it in GitHub Desktop.
Brainfuck in ts
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