Tuesday, May 18, 2010

A Simple Technique for Composing Long Expressions (STCLE)

Reading Doug Crockford's Javascript: The Good Parts book recently, I was surprised to see Crockford drawing attention to the ugliness arising from large Regular Expressions yet overlooking the obvious solution. Throughout the skinny book, Crockford relies on a common Javascript idiom, which is to patch objects with a new method.  In this case, we can patch the RegExp object with a compose method that accepts array-literal notation and returns a RegExp object. Using Crockford's "method" mutator,

Function.prototype.method = function(name, func) {
 if (!this.prototype[name]) { this.prototype[name] = func; return this; }
RegExp.method("compose", function( parts ) {
 var i, r=""; 
 for( i=0; i < parts.length; i+=1) {
   r += (is_array( parts[i]) ? "("+RegExp.prototype.compose(parts[i])+")" : parts[i] ); 
 return r;

Then suppose we call this new method as so:

var re=(new RegExp).compose(
  [ "^",
    [ "?:", ["[A-Za-z]+"], ":"],

What we get is the composed string with array nesting used to imply the presence of groups. Note that the regular expression may now be broken up into multiple lines, and commented heavily, but you still get ^?:([A-Za-z]):)?. A similar technique using array stuffing and the join method is quite useful for creating page output in a manner that avoids most of the output coding. The array is a template, and one just specifies a single join and output command:

var pg = [ 


" "placeholder", "foo" ]; pg.push("

Some stuff

"); document.getElementById("bar").innerHTML = pg.join();

Post a Comment