Last active
December 7, 2016 22:54
-
-
Save dmadisetti/69035bca2c544aa7f15f28dfdb5240c1 to your computer and use it in GitHub Desktop.
Functional JS implementation of Befunge Interpeter
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
const BEFUNGE = ()=>{ | |
var c, r; | |
var s = [], | |
i = 0, | |
j = 0, | |
di = 0, | |
dj = 1, | |
e = 0, | |
set = (a,b)=>{di=b;dj=a}, | |
g = ()=>c[(i+=di) - di][(j+=dj)- dj]; | |
const I = { | |
">": () => set(1,0), | |
"<": () => set(-1,0), | |
"^": () => set(0,-1), | |
"v": () => set(0,1), | |
"?": () => ((x) => set( | |
[0, [1,-1][(x > .75) | 0]][(x > .5) | 0], | |
[0, [1,-1][(x > .25) | 0]][(x <= .5) | 0] | |
))(Math.random()), | |
"+": () => s.push(s.pop() + s.pop()), | |
"-": () => s.push(s.pop() - s.pop()), | |
"*": () => s.push(s.pop() * s.pop()), | |
"/": () => s.push((s.pop() / s.pop())|0), | |
"%": () => s.push(s.pop() % s.pop()), | |
"!": () => s.push((s.pop == 0)|0), | |
"`": () => s.push(s.pop() > s.pop()), | |
"_": () => set(-1 + 2*(s.pop()==0), 0), | |
"|": () => set(0, -1 + 2*(s.pop()==0)), | |
'"': () => {g(); while(c[i][j] != '"'){s.push(c[i][j].charCodeAt(0));g();}}, | |
":": () => s.push(s[s.length-1] | 0), | |
"\\": () => s = s.concat([s.pop(),s.pop()]), | |
"$": () => s.pop(), | |
".": () => r+= s.pop(), | |
",": () => r+= String.fromCharCode(s.pop()), | |
"#": () => g(), | |
"g": () => s.push((c[s.pop()][s.pop()] || "").charCodeAt(0) | 0), | |
"p": () => c[s.pop()][s.pop()] = String.fromCharCode(s.pop()), | |
"&": () => s.push(prompt() | 0), | |
"~": () => s.push(prompt().charCodeAt(0)), | |
"@": () => e = 1, | |
"0": () => s.push(0), | |
"1": () => s.push(1), | |
"2": () => s.push(2), | |
"3": () => s.push(3), | |
"4": () => s.push(4), | |
"5": () => s.push(5), | |
"6": () => s.push(6), | |
"7": () => s.push(7), | |
"8": () => s.push(8), | |
"9": () => s.push(9), | |
" ": () => {} | |
} | |
return (S)=> { | |
c = S.split('\n').filter((x)=>x.length>0); | |
r = ""; | |
while(!e) (I[c[i][j]](),g()); | |
return r; | |
} | |
} | |
var b = BEFUNGE(); | |
console.log(b( | |
` | |
> v | |
v "D" < | |
, ^ $ " y" < | |
, ^ $ " l" < | |
, ^ $" a" < | |
, ^ "n " < | |
, | |
> v | |
v ,"is", < | |
$$ >,v >, $$ v | |
, $ \\ | |
" " " | |
t h e | |
" " " | |
$ | |
> ,^ >,^ | |
vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv | |
v " Illest " < | |
--------------------- | |
> :v | |
v:,_@ | |
> ^ | |
He's other things too, but | |
whatever | |
`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment