Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Stack Snippets were recently added to PPCG! Reminiscent of JSFiddle, Stack Snippets allow HTML, CSS, and JavaScript to be run directly in posts!

Here is a very simple Stack Snippet:

alert('This is JavaScript')
h3 { color: red } /* This is CSS */
<h3>This is HTML</h3>

This feature of Stack Exchange would be very useful for us if languages besides JavaScript were supported. (The answers to challenges could be tested on the spot, example inputs could be generated dynamically, etc.) This is where you come in.

Challenge

The goal of this challenge is to write an interpreter for some programming language using Stack Snippets and JavaScript. The point is to make something that can be easily copied and used in future PPCG questions and answers.

More or less, you need to create a Stack Snippet that has a "run" button and two textboxes, one for code and one for input. Clicking the run button will execute the code (written in the language you're interpreting) on the input and display the result (probably in another textbox). The snippet should be something akin to cjam.aditsu.net or the sample answer.

For most languages it would make sense for the input and output to represent stdin and sdout respectively, and you might have another input box for the command line. But not all languages have have such traditional I/O mechanisms. HQ9+, for example, doesn't even have input, making a textbox for it pointless. So feel free to take some liberties, design around the language, not this spec. The main requirement is that your language be "runnable" in a Stack Snippet in the accepted sense of the term.

Notes

  • Implementing every single feature of your language, though ideal, is not required. Some things like reading and writing files or importing libraries may be unwieldy or impossible. Focus on making an interpreter that maximizes utility for use on this site.
  • Posting a "language X to JavaScript" interpreter that you didn't write is ok (with attribution).
  • Stack Exchange limits answers to 30,000 characters, so plan accordingly if your interpreter is likely to be long.
  • It is best that you make a version of your interpreter as easy as possible to include in future posts. For example, in the sample answer, the raw Markdown for the entire snippet is provided, with obvious places to put code and input.

Although this question is intended to be more a compendium of interpreters than a proper challenge, it is still a , so the highest voted answer wins.

List of Current Interpreters

(sorted alphabetically by language name)

  1. Brainfuck
  2. Deadfish
  3. JavaScript (sample answer)

(This question might be better suited for Meta but it will be more visible here. People might actually produce very useful interpreters, I think they deserve the rep for it.)

share|improve this question
    
Nice idea - now I know what I'll be doing this weekend :) –  Sp3000 17 hours ago
1  
It wouldn't be very fun, but the more practical answer for harder languages like Python would probably be to simply outsource it. –  Sp3000 12 hours ago
    
I have no idea how to run these snippets using the stack exchange app. –  Jerry Jeremiah 11 hours ago
    
I hope someone tackles C with this challenge. Here's a head start: stackoverflow.com/questions/6142193/… –  Adam Davis 6 hours ago
1  

5 Answers 5

Brainfuck

Here's a basic BF interpreter. I think having an interpreter would be more useful for questions where a user might want to try changing the code a little, but otherwise outsourcing the problem might be the neater way of doing it.

On my browser everything is contained within the expanded snippet, but I'm no expert on browser compatibility so I can't guarantee that'll be the same for everybody.

Features:

  • Cell wrapping and EOF behaviour can be configured
  • Timeout can be bypassed
  • Program can be halted mid-execution
  • A nice little clear button
  • All this within the Stack Snippet box (or at least I tried) and clocking in at around 6k chars ungolfed

var NUM_CELLS = 30000
var ITERS_PER_SEC = 100000
var TIMEOUT_MILLISECS = 5000
var ERROR_BRACKET = "Mismatched brackets"
var ERROR_TIMEOUT = "Timeout"
var ERROR_INTERRUPT = "Interrupted by user"

var code, input, wrap, timeout, eof, loop_stack, loop_map
var running, start_time, code_ptr, input_ptr, cell_ptr, cells, iterations

function clear_output() {
  document.getElementById("output").value = ""
  document.getElementById("stderr").innerHTML = ""
}

function stop() {
  running = false
  document.getElementById("run").disabled = false
  document.getElementById("stop").disabled = true
  document.getElementById("clear").disabled = false
  document.getElementById("wrap").disabled = false
  document.getElementById("timeout").disabled = false
  document.getElementById("eof").disabled = false
}

function interrupt() {
  error(ERROR_INTERRUPT)
}

function error(msg) {
  document.getElementById("stderr").innerHTML = msg
  stop()
}

function run() {
  clear_output()
  
  document.getElementById("run").disabled = true
  document.getElementById("stop").disabled = false
  document.getElementById("clear").disabled = true
  document.getElementById("wrap").disabled = true
  document.getElementById("timeout").disabled = true
  document.getElementById("eof").disabled = true

  code = document.getElementById("code").value
  input = document.getElementById("input").value
  wrap = document.getElementById("wrap").value
  timeout = document.getElementById("timeout").checked
  eof = document.getElementById("eof").value

  loop_stack = []
  loop_map = {}

  for (var i = 0; i < code.length; ++i) {
    if (code[i] == "[") {
      loop_stack.push(i)

    } else if (code[i] == "]") {
      if (loop_stack.length == 0) {
        error(ERROR_BRACKET)
        return

      } else {
        var last_bracket = loop_stack.pop()
        loop_map[last_bracket] = i
        loop_map[i] = last_bracket
      }
    }
  }

  if (loop_stack.length > 0) {
    error(ERROR_BRACKET)
    return
  }

  running = true
  start_time = Date.now()
  code_ptr = 0
  input_ptr = 0
  cell_ptr = Math.floor(NUM_CELLS / 2)
  cells = {}
  iterations = 0

  bf_iter(1)
}

function bf_iter(niters) {
  if (code_ptr >= code.length || !running) {
    stop()
    return
  }

  var iter_start_time = Date.now()

  for (var i = 0; i < niters; ++i) {
    if (cells[cell_ptr] == undefined) {
      cells[cell_ptr] = 0
    }

    switch (code[code_ptr]) {
      case "+":
        if ((wrap == "8" && cells[cell_ptr] == 255) ||
            (wrap == "16" && cells[cell_ptr] == 65535) || 
            (wrap == "32" && cells[cell_ptr] == 2147483647)) {
            cells[cell_ptr] = 0
        } else {
          cells[cell_ptr]++
        }
        break
        
      case "-":
        if (cells[cell_ptr] == 0){
          if (wrap == "8"){ cells[cell_ptr] = 255 }
          if (wrap == "16"){ cells[cell_ptr] = 65535 }
          if (wrap == "32"){ cells[cell_ptr] = 2147483647 }    
        } else {
          cells[cell_ptr]--
        }
        break
      
      case "<": cell_ptr--; break
      case ">": cell_ptr++; break

      case ".":
        document.getElementById("output").value += String.fromCharCode(cells[cell_ptr])
        break

      case ",":
        if (input_ptr >= input.length) {
          if (eof != "nochange") {
            cells[cell_ptr] = parseInt(eof)
          }
        } else {
          cells[cell_ptr] = input.charCodeAt(input_ptr)
          input_ptr++
        }
        break

      case "[":
        if (cells[cell_ptr] == 0) {
          code_ptr = loop_map[code_ptr]
        }
        break

      case "]":
        if (cells[cell_ptr] != 0) {
          code_ptr = loop_map[code_ptr]
        }
        break
    }

    code_ptr++
    iterations++

    if (timeout && Date.now() - start_time > TIMEOUT_MILLISECS) {
      error(ERROR_TIMEOUT)
      return
    }
  }

  setTimeout(function() { bf_iter(ITERS_PER_SEC * (Date.now() - iter_start_time)/1000) }, 0)
}
textarea {
  width: 90%;
}

#snippet {
  font-size: 12px;
  font-family: Verdana, Geneva, sans-serif;
}
<div id="snippet">
  <div style="float:left; width:50%;">
    Code:
    <br>
    <textarea id="code" rows="4" style="overflow:scroll;overflow-x:hidden">>++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>>+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.</textarea>
    <br>Input:
    <br>
    <textarea id="input" rows="2" style="overflow:scroll;overflow-x:hidden"></textarea>
    <p>
      Wrap:
      <select id="wrap">
        <option value="8">8-bit</option>
        <option value="16">16-bit</option>
        <option value="32">32-bit</option>
      </select>
      &nbsp;
      Timeout:
      <input id="timeout" type="checkbox" checked="true"></input>&nbsp; EOF:
      <select id="eof">
        <option value="nochange">Same</option>
        <option value="0">0</option>
        <option value="-1">-1</option>
      </select>
    </p>
  </div>
  <div style="float:left; width:50%;">
    Output:
    <br>
    <textarea id="output" rows="6" style="overflow:scroll;"></textarea>
    <p>
      <input id="run" type="button" value="Run" onclick="run()"></input>
      <input id="stop" type="button" value="Stop" onclick="interrupt()" disabled="true"></input>
      <input id="clear" type="button" value="Clear" onclick="clear_output()"></input>
      &nbsp;
      <span id="stderr" style="color:red"></span>
    </p>
  </div>
</div>

share|improve this answer

Deadfish

I'm not proficient in JS/HTML/CSS, so I thought I'd take something easy so that we can experiment a little with the input/output layout.

This one works best if you full page it.

function run() {
  var code = document.getElementById("code").value
  var unicode = document.getElementById("unicode").checked
  var n = 0
  var output = ""

  for (var i = 0; i < code.length; ++i) {
    switch (code[i]) {
      case "i":
        n++
        break
      case "d":
        n--
        break
      case "s":
        n *= n
        break
      case "o":
        if (unicode) {
          output += String.fromCharCode(n)
        } else {
          output += n
          output += "\n"
        }
        break
      default:
        output += "\n"
    }
    
    if (n == -1 || n == 256) {
      n = 0
    }
  }

  document.getElementById('output').value = output
}
<h1>Deadfish interpreter</h1>
<h2>Code</h2>
<textarea id="code" rows="12" cols="80" style="overflow:scroll;overflow-x:hidden;resize:none" wrap="hard"></textarea>
<p>
  <input id="unicode" type="checkbox">Use ASCII/Unicode mode</input>
</p>
<p>
  <input id='run' type='button' value='Run' onclick='run()'></input>
</p>
<br>
<h2>Output</h2>
<textarea id="output" rows="12" cols="80" style="overflow:scroll"></textarea>

To pre-initialise the code box, just put something in between the textarea tags. Similarly, you can add checked="true" for the checkbox tag to have ASCII/Unicode mode on by default.

Example from the Happy Birthday topic:

function run() {
  var code = document.getElementById("code").value
  var unicode = document.getElementById("unicode").checked
  var n = 0
  var output = ""

  for (var i = 0; i < code.length; ++i) {
    switch (code[i]) {
      case "i":
        n++
        break
      case "d":
        n--
        break
      case "s":
        n *= n
        break
      case "o":
        if (unicode) {
          output += String.fromCharCode(n)
        } else {
          output += n
          output += "\n"
        }
        break
      default:
        output += "\n"
    }
    
    if (n == -1 || n == 256) {
      n = 0
    }
  }

  document.getElementById('output').value = output
}
<h1>Deadfish interpreter</h1>
<h2>Code</h2>
<textarea id="code" rows="12" cols="80" style="overflow:scroll;overflow-x:hidden;resize:none" wrap="hard">iiisdsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiiofdddddddddddddddddddddddddddddddddddddddddddddoiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiiofdddddddddddddddddddddddddddddddddddddddddddddoiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiiiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioddddoiiiiiiiiiiiiiiiiioddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiiiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioddddoiiioiioiiioiiiiiiiiiiodddddddddddofddddddddddddddddddddddddddddddddoiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiio </textarea>
<p>
  <input id="unicode" checked="true" type="checkbox">Use ASCII/Unicode mode</input>
</p>
<p>
  <input id='run' type='button' value='Run' onclick='run()'></input>
</p>
<br>
<h2>Output</h2>
<textarea id="output" rows="12" cols="80" style="overflow:scroll"></textarea>

share|improve this answer

Python (No STDIN)

Thanks to Skulpt, it has become very easy to write a Python interpreter.

function out(text) {
  var output = document.getElementById("output");
  output.innerHTML = output.innerHTML + text;
}

function builtinRead(x) {
  if(Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
    throw "File not found: '" + x + "'";
  return Sk.builtinFiles["files"][x];
}

function run() {
  var program = document.getElementById("python-in").value;
  var output = document.getElementById("output");
  
  output.innerHTML = "";
  
  Sk.canvas = "canvas";
  Sk.pre = "output";
  
  Sk.configure({
    output: out,
    read: builtinRead
  });
  
  try {
    Sk.importMainWithBody("<stdin>", false, program);
  }
  catch(e) {
    throw new Error(e.toString());
  }
}
#python-in {
  border-radius: 3px;
  background: rgb(250, 250, 250);
  width: 95%;
  height: 200px;
}

#output {
  border-radius: 3px;
  background: lightgray;
  width: 95%;
  height: 200px;
}

#canvas {
  border: 1px solid gray;
  border-radius: 3px;
  height: 400px;
  width: 400px;
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://crash-revision.ueuo.com/skulpt.js"></script>
<script src="http://crash-revision.ueuo.com/builtin.js"></script>

Python code:<br/>
<textarea id="python-in" name="python-in" rows="10" cols="80"></textarea><br/>
<button id="run-code" onclick="run()">Run</button><br/>
<br/>

Output:<br/>
<pre id="output" name="output" rows="10" cols="10" disabled></pre><br/>

Canvas for turtles:<br/>
<canvas height="400" width="400" id="canvas">Your browser does not support HTML5 Canvas!</canvas>

No STDIN, but it's a pretty complete implementation of Python in JS. I would load the libraries from somewhere else but I can't find a host of them.

share|improve this answer

Deadfish

This does not conform strictly to the requirement, it is my vision on how we could make use of Stack Snippets.

I don't like the amount of boilerplate, especially the need to include custom HTML for another Run button.

In my vision:

  • place a single <script> tag to include a simple framework and the actual interpreter
  • put the script in the CSS area (syntax highlighting may go horrible)
  • use the existing Run code snippet button to run the code
  • get the output in the snippet frame

For now not decided how would be nicer to specify the input.

iiisdsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiio
dddddddddddddddddddddddddddddddddddddddddddddoiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiio
dddddddddddddddddddddddddddddddddddddddddddddoiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiiiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioddddoiiiiiiiiiiiiiiiiioddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiiiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioddddoiiioiioiiioiiiiiiiiiiodddddddddddo
ddddddddddddddddddddddddddddddddoiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiiiiiiiiooiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddoddddddddddddddddddddddddsiioiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiioiiiiiiiiioiioddddddddddddoddddodddoiiiiiiiiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddsdddddodddddodddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddodddddddddddddddddddddddsiiiiiiiioiiiiiiiiiiiiiiiiiiiiiioiiiiiio
<script src="https://bitbucket.org/manatwork/stackcode/raw/eca705e41c57de88f682d3e7223d4efa90a9a693/interpret.js#Deadfish"></script>

share|improve this answer
    
there should be a way to easily include the input as well I guess –  SztupY 7 hours ago
    
Certainly, @SztupY. For now I am undecided whether to include the input also in the CSS piece or in the HTML one. Would not use the JavaScript piece for that, as the browsers will execute it before and some code may result endless loop in JavaScript. Sadly, there is no other way as other pieces are not copied over to the stack snippets server. :( –  manatwork 7 hours ago
    
I think the code is fine in the CSS, and the input can go after the <script> tags (maybe in a small container, like <pre>, so the script could get access to it. Hopefully a pre wouldn't distort the input much as well). –  SztupY 7 hours ago
    
A <pre> (or generally any tag) would appear displayed and syntax highlighted in green. As JavaScript is able to extract the input part anyway, I would not include extra markup. The main difference between using the CSS piece vs. the HTML piece is that CSS not appears in the document, while HTML does. Still undecided. –  manatwork 6 hours ago
    
Good idea. Though loading the code from a non-SE site goes against the idea of being self contained, so I'd avoid it if possible. –  Calvin's Hobbies 4 hours ago

JavaScript (sample answer)

Interpreting JavaScript using JavaScript is somewhat useless, but this shows what your interpreter snippets should roughly behave like.

Here is the bare bones version, intended for quick use in other posts. To use it with preinitialized code and input you only need to copy the snippet and reassign the code and input variables in the first script tag.

<script>
code = "//PUT JAVASCRIPT CODE HERE"
input = "PUT INPUT HERE"
//IGNORE EVERYTHING BELOW
</script>JavaScript:<br><tt>function(x) {</tt><br><textarea id='c'rows='4'cols='60'></textarea><br><tt>}</tt><br><br>Input string (global variable x):<br><textarea id='i'rows='4'cols='60'></textarea><p><input type='button'value='Run'onclick='r()'></p>Output (global variable y):<br><textarea id='o'rows='4'cols='60'style='background-color:#f0f0f0;'></textarea><script>document.getElementById('c').value=code;document.getElementById('i').value=input;function r(){var r=null,code=null,input=null;eval('var f=function(x) {'+document.getElementById('c').value+'}');document.getElementById('o').value=String(f(document.getElementById('i').value))}</script>

The raw Markdown for including this Stack Snippet in a post is:

<!-- begin snippet: js hide: false -->
<!-- language: lang-html -->
    <script>
    code = "//PUT JAVASCRIPT CODE HERE"
    input = "PUT INPUT HERE"
    //IGNORE EVERYTHING BELOW
    </script>JavaScript:<br><tt>function(x) {</tt><br><textarea id='c'rows='4'cols='60'></textarea><br><tt>}</tt><br><br>Input string (global variable x):<br><textarea id='i'rows='4'cols='60'></textarea><p><input type='button'value='Run'onclick='r()'></p>Output (global variable y):<br><textarea id='o'rows='4'cols='60'style='background-color:#f0f0f0;'></textarea><script>document.getElementById('c').value=code;document.getElementById('i').value=input;function r(){var r=null,code=null,input=null;eval('var f=function(x) {'+document.getElementById('c').value+'}');document.getElementById('o').value=String(f(document.getElementById('i').value))}</script>
<!-- end snippet -->

Below is the ungolfed general version, complete with example and a bit more styling.

function example() {
  document.getElementById('code').value = "var lines = x.split('\\n')\nvar sum = 0\nfor (var i = 0; i < lines.length; i++) {\n  var val = parseInt(lines[i])\n  if (!isNaN(val)) {\n    sum += val\n  }\n}\nreturn sum"
  document.getElementById('input').value = '1\n2\n3'
  run()
}

function run() {
  var run = null, example = null; //shadow other globals
  eval('var f=function(x) {' + document.getElementById('code').value + '}')
  document.getElementById('output').value = String(f(document.getElementById('input').value))
}
#output {
  background-color: #f0f0f0;
}

#run {
  font-size: 120%;
}
JavaScript:<br>
<tt>function(x) {</tt>
<br>
<textarea id='code' rows='12' cols='60'></textarea>
<br><tt>}</tt><br><br>
Input string (variable x):
<br>
<textarea id='input' rows='6' cols='60'></textarea>
<p><input id='run' type='button' value='Run' onclick='run()'></p>
Output (return value):
<br>
<textarea id='output' rows='6' cols='60'></textarea>
<p><a id='example' href='javascript:void(0)' onclick='example()'>Example: Sum Numbers</a></p>

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.