validate musical note

JavaScript performance comparison

Test case created by ju1ius

Preparation code

<script>
  var NOTES = {
        'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11
      },
      NOTE_RX = /^[A-Ga-g][#b]*$/,
      VALID_NOTES = [
        'G#', 'Ab', 'B##', 'Cbb#', 'Ebbbbb',
        'G#', 'Ab', 'B##', 'Cbb#', 'Ebbbbb'
      ],
      INVALID_NOTES = [
        'Rt', 'Feee', 'Foo', 'Barrr', 'C##bo', 'Abb####oo',
        'Rt', 'Feee', 'Foo', 'Barrr', 'C##bo', 'Abb####oo'
      ];

  function validateNote(name)
  {
    var i, l, alt;
    if(!NOTES.hasOwnProperty(name[0])) {
      return false;
    }
    for(i = 1, l = name.length; i < l; ++i) {
      alt = name[i];
      if(alt !== 'b' && alt !== '#') return false;
    }
    return true;
  }
  function validateNoteRegex(name)
  {
    return NOTE_RX.test(name);
  }
  function cacheDecorator(fn)
  {
    var cache = {};
    return function(input) {
      if(cache.hasOwnProperty(input)) {
        return cache[input];
      }
      var output = fn.apply(null, arguments);
      cache[input] = output;
      return output;
    }
  }
  var validateNoteCached = cacheDecorator(validateNote);
  var validateNoteRegexCached = cacheDecorator(validateNoteRegex);

  function doTest(fn, values, shouldValidate)
  {
    values.forEach(function(note){
      var result = fn(note);
      if (result !== shouldValidate) {
        console.log(result);
        throw new Error(fn.name +
          " should " + (shouldValidate ? "" : "not ") +
          "validate note " + note
        );
      }
    });
  }
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
validate with hasOwnProperty + for loop
doTest(validateNote, VALID_NOTES, true);
doTest(validateNote, INVALID_NOTES, false);
pending…
validate with regex
doTest(validateNoteRegex, VALID_NOTES, true);
doTest(validateNoteRegex, INVALID_NOTES, false);
pending…
test 1 with cache
doTest(validateNoteCached, VALID_NOTES, true);
doTest(validateNoteCached, INVALID_NOTES, false);
pending…
test 2 with cache
doTest(validateNoteRegexCached, VALID_NOTES, true);
doTest(validateNoteRegexCached, INVALID_NOTES, false);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment