validate musical note
JavaScript performance comparison
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',
'G#', 'Ab', 'B##', 'Cbb#', 'Ebbbbb',
'G#', 'Ab', 'B##', 'Cbb#', 'Ebbbbb',
'G#', 'Ab', 'B##', 'Cbb#', 'Ebbbbb',
'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',
'Rt', 'Feee', 'Foo', 'Barrr', 'C##bo', 'Abb####oo',
'Rt', 'Feee', 'Foo', 'Barrr', 'C##bo', 'Abb####oo',
'Rt', 'Feee', 'Foo', 'Barrr', 'C##bo', 'Abb####oo',
'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.
| Test | Ops/sec | |
|---|---|---|
validate with hasOwnProperty + for loop |
|
pending… |
validate with regex |
|
pending… |
test 1 with cache |
|
pending… |
test 2 with cache |
|
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:
- Revision 1: published by ju1ius
- Revision 2: published
0 comments