Three Monkeys, Three Typewriters, Two Days

April 16, 2008

Array.map + destructuring assignment = win

It's nice to write code sometimes unburdened by either C++ or performance considerations. It can just look so nice as a result!

function stringToURL(str) {
  return (new StandardURL(nsIStandardURL.URLTYPE_AUTHORITY, 80,
                         str, "UTF-8", null))
         .QueryInterface(Components.interfaces.nsIURL);
}

function pairToURLs(pair) {
  do_check_eq(pair.length, 2);
  return pair.map(stringToURL);
}

function test_setQuery()
{
  var pairs =
    [
     ["http://example.com", "http://example.com/?foo"],
     /* more pairs here */
    ].map(pairToURLs);
  for each (var [provided, target] in pairs) {
    /* Set the query and test for equality here */
  }
}
Posted by bzbarsky at April 16, 2008 12:34 AM | TrackBack
Comments

Indeed-o!

Posted by: mmc on April 16, 2008 3:40 AM

Actually, I think you can do it nicer, and maybe even perfier, but you need to switch js1.7 on:

function enumURLPairs(list) {
for each (var tuple in list) {
do_check_eq(tuple.length, 2);
yield tuple.map(stringToURL);
}
}

for each (var [provided, target] in enumURLPairs(paris) {
// do foo
}

This way you don't create the intermediate array.

PS: Sorry, I don't think I can indent.

Posted by: Axel Hecht on April 16, 2008 8:17 AM
Post a comment