Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Expression Thingy</title>
  <style>
    .good {
      color: green;
    }
    .bad {
      color: #d22;
    }
  </style>
</head>
<body>
  <script>
    (function() {
      var data = ["red", "blue", "neon", "black", "orange"];
      var tests = [
        {expr: "red&&blue",                 expect: true},
        {expr: "blue&&white",               expect: false},
        {expr: "red,white",                 expect: true},
        {expr: "(red&&blue),(red&&white)",  expect: true},
        {expr: "(red&&blue)&&(red&&white)", expect: false},
        {expr: "(red&&blue)&&(red&&neon)",  expect: true}
      ];
      var obj;
      
      // Turn data into an object with named properties
      obj = {};
      data.forEach(function(entry) {
        obj[entry] = true;
      });
      
      // Turn the expressions into eval strings
      tests.forEach(createEvalString);
      
      // Run the tests
      tests.forEach(runTest);
      
      function createEvalString(test) {
        test.evalStr = test.expr.replace(/,/g, "||").replace(/\b([a-zA-Z0-9_]+)\b/g, 'obj["$1"]');
      }
      
      function runTest(test) {
        var result;
        
        display(test.evalStr);
        result = !!eval(test.evalStr); // Relies on us closing over `obj`
        display(test.expr + ": Got " + result + ", expected " + test.expect, result === test.expect);
      }
      
      function display(msg, good) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        if (typeof good !== "undefined") {
          p.className = good ? "good" : "bad";
        }
        document.body.appendChild(p);
      }
    })();
  </script>
</body>
</html>
Output

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

Dismiss x
public
Bin info
anonymouspro
0viewers