Thursday, June 3, 2010

Multiple return values in Javascript

While writing some javascript few days ago I encountered one case where it was really nice to be able to return multiple values from function. Usually you pack your return values in array, return that array and unpack it at call site. While creating array with values is easy in javascript, unpacking those values back is neither elegant, nor short. Because javascript (portable subset at least) have no destructuring. E.g. code normally looks like this:

  function findRoutingFor(method, path) {
    var foundRoute, routeArgs;
    // some computation here

    if (foundRoute)
        return [foundRoute, routeArgs];
  }

  // and at call site
  var rv = findRoutingFor(method, path);
  if (!rv)
     throw new Error(/* */);
  var foundRoute = rv[0];
  var routeArgs = rv[1];

I believe, that I came up with more elegant way to do that. Continuation passing style saves us here. Here's how:

  // notice extra parameter
  function findRoutingFor(method, path, body) {
    var foundRoute, routeArgs;
    // same computation here
    // and then we invoke continuation
    return body(foundRoute, routeArgs);
  }

  // then at call site...
  return findRoutingFor(method, path, function (foundRoute, routeArgs) {
    if (!foundRoute)
      throw new Error(/* */);
    // rest of call site is here
  });

So continuation passing style allows us to avoid packing & unpacking of multiple return values. There are some costs, like, for example, extra indentation of rest of call site, but, IMO, in many cases it's better than usual alternative.

No comments:

Post a Comment