You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@couchdb.apache.org by Samuel Wan <sa...@samuelwan.com> on 2009/05/14 23:59:29 UTC

a shorter patchTest function

I was trying to get the test suite to run on the Helma server's Rhino
interpreter. In the process of trying to understand the patchTest
function, I shortened it using regexp. I'm new to this stuff, so if
you find this useful, a code critique would be appreciated :) I'm not
sure if the second parameter needs escaping...

// Shortened
function patchTest(fun) {
  var output = fun.toString().replace(/T\((.*)\);/g, "T($1" + "," + "'$1');");
  try {
    return eval("(" + output + ")");
  } catch (e) {
    return null;
  }
}

// Original
function patchTest(fun) {
  var source = fun.toString();
  var output = "";
  var i = 0;
  var testMarker = "T("
  while (i < source.length) {
    var testStart = source.indexOf(testMarker, i);
    if (testStart == -1) {
      output = output + source.substring(i, source.length);
      break;
    }
    var testEnd = source.indexOf(");", testStart);
    var testCode = source.substring(testStart + testMarker.length, testEnd);
    output += source.substring(i, testStart) + "T(" + testCode + "," +
JSON.stringify(testCode);
    i = testEnd;
  }
  try {
    return eval("(" + output + ")");
  } catch (e) {
    return null;
  }
}
-Sam