Skip to content

Instantly share code, notes, and snippets.

@st98
Last active August 29, 2015 14:13
Show Gist options
  • Save st98/01c7aa196524c04f77e0 to your computer and use it in GitHub Desktop.
Save st98/01c7aa196524c04f77e0 to your computer and use it in GitHub Desktop.
Brainf*ck を JavaScript に変換するヤツ。
parse = (prog) ->
prog = prog.replace /[^><\[\],.+-]/g, ''
if prog.length is 0
return []
c = 0
result = (prog.match /([+]+|[-]+|[>]+|[<]+|.)/g).map (m) ->
if m[0] is '['
c++
if m[0] is ']'
c--
if m[0] in '+-><'
return [m[0], m.length.toString()]
else
return [m]
if c isnt 0
throw new SyntaxError
result
convert = do ->
repeat = (s, i) ->
result = ''
while i--
result += s
result
header = '''
;(function () {
var memory = new Uint8Array(30000);
var pointer = 0;
var output = [];
'''
footer = '''
console.log(String.fromCharCode.apply(null, output));
}).call(this);
'''
(prog) ->
result = header
prog = parse prog
depth = 1
for t in prog
if t[0] is ']'
depth--
result += repeat ' ', depth
result += switch t[0]
when '+' then 'memory[pointer] += ' + t[1] + ';'
when '-' then 'memory[pointer] -= ' + t[1] + ';'
when '>' then 'pointer += ' + t[1] + ';'
when '<' then 'pointer -= ' + t[1] + ';'
when '[' then 'while (memory[pointer]) {'
when ']' then '}'
when ',' then "memory[pointer] = prompt('').charCodeAt(0) || 0;"
when '.' then 'output.push(memory[pointer]);'
if t[0] is '['
depth++
result += '\n'
result + footer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment