Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>sum</title>
</head>
<body>
  <div>
    <p>Items (separated by whitespace):</p>
    <textarea rows="8" cols="80" id="items"></textarea>
  </div>
  <div>
    <p>Function:</p>
    <textarea rows="8" cols="80" id="fn"></textarea>
  </div>
  <div>
    <p>Result:</p>
    <textarea rows="8" cols="80" id="result"></textarea>
  </div>
  <script>
    function setDefaultValues() {
      
      var fnField = document.getElementById('fn');
      fnField.value = [
        'function(items) {',
        '  return items.reduce(function(acc, s) {',
        '    return acc + parseInt(s, 10);',
        '  }, 0);',
        '}'
      ].join("\n");
      var itemField = document.getElementById('items');
      itemField.value = [1, 2, 3].join("\n");
    }
    
    function splitWhitespace(str) {
      return str.split(/\s+/).filter(function(s) { return s.length > 0; });
    }
    
    function makeFunction(src) {
      return Function('__arg__',
                      'return (' + src + ').call(null, __arg__)');
    }
    
    function computeResult() {
      var itemField = document.getElementById('items');
      var fnField = document.getElementById('fn');
      var resultField = document.getElementById('result');
      resultField.value = '';
      var items = splitWhitespace(itemField.value);
      var fn = makeFunction(fnField.value);
      var result = fn(items);
      resultField.value = JSON.stringify(result);
    }
    
    function attachEvents() {
      var elements = document.querySelectorAll('textarea');
      var el;
      for (var i=0; i < elements.length; i++) {
        el = elements[i];
        el.addEventListener('blur', function(e) {
          computeResult();
        });
      }
    }
    
    setDefaultValues();
    computeResult();
    attachEvents();
  </script>
</body>
</html>
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
benatkinpro
0viewers