Javascript feels like Perl

Ovid on 2005-10-18T18:09:17

I really have to admire how Perlish Javascript seems to be at times. Of course, that could be how I'm using it:

_getComparison: function (elem, type) {
    var name  = elem.name;
    var regex = new RegExp("^_([^_]*)_" + type);
    name      = name.replace(regex, "$1");

    if (! name) return;
    var value = "";
    if (elem.options) {
        value = elem.options[elem.selectedIndex].value;
        value = value ? value : "";
    }
    return {
        "name"  : name,
        "value" : value
    };
},

Oh, but that's a bit complicated. I had better have tests.

canOK('FormHandler.Search', '_getComparison');
var elem = document.search._age_comp;
var results = search._getComparison(elem, 'comp');
is(results["name"], "age", 
  '... and it should return the name of the property it refers to');
is(results["value"], "GT", 
  '... and the value of the comparison property');

elem = document.search._age_logical;
results = search._getComparison(elem, 'logical');
is(results["name"], "age", 
  '... and a logical comparison should return the property name');
is(results["value"], "",
  '... but it should return an empty string if there is no value');

And the results:

ok 18 - FormHandler.Search.can('_getComparison')
ok 19 - ... and it should return the name of the property it refers to
ok 20 - ... and the value of the comparison property
ok 21 - ... and a logical comparison should return the property name
ok 22 - ... but it should return an empty string if there is no value


From jsregexp.c in SpiderMonkey

claes on 2005-10-18T18:49:46

/*
* JS regular expressions, after Perl.
*/