JSFiddle - React, Tailwind, and code Playground

by prankol57

HTML

Upload the text file with test cases here:
<input type="file" /><br />
<textarea placeholder="enter code here" rows="20"></textarea>
<button>Test</button>
<p id="result">

</p>
<p id="chars">
</p>

JavaScript

document.querySelector("button").onclick = function() {
	var inp = document.querySelector("input");
  var f = inp.files[0];
  if (f == null) return;
  var r = new FileReader();
  r.onload = function(e) {
  	var content = e.target.result, code;
    content = content.replace(/\r/g, '');
    var fn = new Function("p", code = document.querySelector('textarea').value);
    document.querySelector("#result").innerHTML = (testFn(content, fn).join(" out of "));
    document.querySelector("#chars").innerHTML = code.length + " characters"
  };
  r.readAsText(f);
};

var testFn = function(text, fn) {
	var lines = text.split("\n");
  var candidates = ['Carson', 'Cruz', 'Kasich', 'Rubio', 'Trump', 'Clinton', 'Sanders'];
  var firsts = ['Ben', 'Ted', 'John', 'Marco', 'Donald', 'Hillary', 'Bernie'];
  var curC = -1;
  var total = 0, totalCorrect = 0;
  for (var i = 0; i < lines.length; ++i) {
  	if (lines[i] === '') continue;
  	if (/^CANDIDATE/.test(lines[i])) {
    	var lName = lines[i].replace("CANDIDATE ", "")
    	curC = candidates.indexOf(lName);
      if (curC === -1) throw new Error("-1 index '" + lName + "'");
      continue;
    }
    else {
    	var quotes = lines[i].split("(NEXT PARAGRAPH)-");
      var correct = 0;
      for (var j = 0; j < quotes.length; ++j) {
      	if (quotes[j] === '') continue;
      	var result = fn(quotes[j]);
        var fullName = firsts[curC] + ' ' + candidates[curC];
        if (result === curC + 1 || result === candidates[curC] || result === fullName) {
        		correct++; 
        }
      }
      totalCorrect += correct;
      total += quotes.length;
    }
  }
  return [totalCorrect, total];
};