More syntactic sugar for Prototype

written by Tobie on July 11th, 2006 @ 11:32 AM

I recently posted a comment on Justin Palmer’s blog about spicing up Prototype with the following ruby flavored function (which is just shorthand for creating arrays):

function $w(string){
  string = string.strip();
  return string ? string.split(/\s+/) : [];
}

$w() trades a bit of execution time against kb saving and expressiveness. Compare the following:

$w('div span p ul ol li dl dt em strong')

against the longer (and more error prone):

['div', 'span', 'p', 'ul', 'ol', 'li', 'dl', 'dt', 'em', 'strong']

As Thomas Fuchs aka Mr. Scriptaculous commented about this function in one of his posts, I couldn’t resist in blogging about it and proposing a patch for it. Thanks, Thomas, for the thumbs up!

So if it is accepted, you will be able to dwell in $w() nicety and write the following kind of beautiful (and in this case rather useless) code:

$w('div p span ul').each(function(tag){
  alert(tag);
});

and if not, you can always stick $w() at the bottom of prototype.js and go ahead using it.

Update: this code is now downloadable as part of xPrototype, my tiny add-on to Prototype.

Update: this is now part of Prototype 1.5.

Comments

  • I like this. I will definitely be including this in my applications. Thanks for the great code!

    Fri, August 11 at 00:26 AM

Comments are closed