Sunday, August 24, 2008

Arrows in Javascript

Last year, I mentioned a lesson I learned from one of my CS professors many years ago:

He began by recommending every project start by hiring a mathematician for a week or two to study the problem. If a mathematician could find an interesting property or algorithm, then it would be money well spent, and drastically reduce the time/money/effort needed to develop a system.

A few weeks ago, I came across a paper about Arrows in Javascript. It's an interesting adaptation of arrows to do asynchronous, event driven programming in Javascript. It makes an excellent example of this dictum.

Here's the problem in a nutshell. There's a very interesting language lurking underneath Javascript. It's an object oriented language with namespaces, closures, and dynamic typing. Doug Crockford has written and presented these concepts over the last few years.

As good as the Javascript is on its own merits (albeit abused and misunderstood), it is generally used in a pretty horrendous environment. Browsers have compatibility bugs in their language support and the cross platform APIs they expose. Most of all, browsers execute Javascript in a single-threaded manner. This makes asynchronous programming difficult, especially when there are two interwoven threads of execution, like drag and drop and dynamic page updates.

This paper by a team at UMD starts by bringing continuation passing to Javascript, and implementing arrows on top of that. Once arrows are available, building a library for asynchronous event programming is much easier than brute force chaining of event callbacks. For example, drag and drop programming can be specified common method chaining:


ConstA(document.getElementById(”dragtarget”))
.next(EventA(”mouseover”))
.next(setupA)
.next(dragDropCancelA)
.run ()

The plumbing inside the library can be a little hairy, especially if you find CPS or arrows befuddling. But the exposed API is quite elegant and appears to be easy to use. It'll be interesting to watch the Javascript library space to see when and where it pops up.