Javascript instant iterators

Sunday, 9 Jan 2005

Today’s useful Javascript snippet:

function iterate( iterable ) {
  var i = -1;
  var iterator = function() { return i < 0 ? null : i < iterable.length ? iterable[ i ] : null; };
  iterator.next = function() { return ( i + 1 ) < iterable.length ? iterable[ ++i ] : null; };
  return iterator;
}

As a Perl-spoiled brat, I find myself using this or a slight variation on it pretty often. It enables me to write the following:

for( var sheet = iterate( document.styleSheets ); sheet.next(); ) {
  if( sheet().href ) {
    do_something( sheet() );
  }
}

rather than the far more tedious and annoyingly repetitive:

for( var i = 0; i < document.styleSheets.length; ++i ) {
  var sheet = document.styleSheets[ i ];
  if( sheet.href ) {
    do_something( sheet );
  }
}

to say nothing of:

for( var i = 0; i < document.styleSheets.length; ++i ) {
  if( document.styleSheets[ i ].href ) {
    do_something( document.styleSheets[ i ] );
  }
}

And of course these are just silly examples. In real code, where you often want to nest several loops, the repetition gets hideous real quick like.