Perl for munging Java-esque Javascript

renodino on 2007-12-30T00:49:32

Javascript's prototype object system may be academically interesting, but its a royal PITA for coding decent class hierachies. (Just do a quick google on "javascript inheritance" and you'll see the madness that makes Perl's OO look like the purest of Smalltalk).

Most of the solutions I've seen tend to be bloated, slow, and only marginally less ugly than the original prototype wrangling they attempt to avoid.

As I'm in the process of bringing DBIx::Chart into the 21st century, I'm wrangling a lot of Javascript. And the long overdue refactoring of the rendering engine means a lot of object hierachies. But typing all the "ThisLongClassname.prototype.someFunction = function..." nonsense is really annoying, and jumping thru all the hoops to properly propagate methods up the class chain is a mind numbing exersize, not to mention an unreadable mess.

So I think, "Someone must have written a preprocessor for this stuff.". While Google turns up a few hits, they all appear to be full-blown Java to Javascript translators. All I need is something to bury the OO yak shaving; while the Java class declaration syntax is a reasonable choice, I don't want to carry all the other bloated baggage. And CPAN has loads of Javascripty modules, but none that address my little task.

Ergo...I've whipped up some Perl to do the translation, and the result is actually pretty reasonable. Just declare classes like

class Parent {
	Parent(first, last) {
		this.first = first;
		this.last = last;
	}
	
	toString() { return this.first + " " + this.last; }
}

class Child extends Parent {
	Child(first, last, id) {
		super(first, last);
		this.id = id;
	}
	
	toString() { return super.toString() + " " + this.id; }
}

et voila, (and with the aid of a very tiny Javascript helper function), the Perl script emits the Javascript with all the prototype crud.

Which will save me many hours of typing and eyestrain. I spose I should CPANify it at some point...

Hmmm. A Perl script to convert Java syntax to Javascript prototyped class hierachies so I can display charts rendered using an extended SQL syntax inside HTML pages.

Anyone looking to hire a polyglot programmer ?