One of the cool things about JavaScript 1.7 is the fact that it supports generator functions. Unfortunately, not all browsers support generator functions yet. Therefore, when creating iterators we can look to an interesting alternative: closures. For example, if our goal was to make a String prototype function which would return an iterator that would iterate through the instances of a specified substring, what could the code look like. Here is my solution:

String.prototype.indexOfIter = function(target) {
  var me = this, len = target.length || 1, index = -len, lastIndex;
  return function() {
    lastIndex = index;
    index = me.slice(lastIndex + len).indexOf(target);
    if(index < 0 || (index += lastIndex + len) > me.length) {
      index = -len;
      return -1;
    }
    return index;
  };
};

The following is an example showing how to display all of the indices of the lowercase letter “L” in the string “Hello world!!!”:

var index, str = "Hello world!!!", iter = str.indexOfIter("l");
while((index = iter()) != -1) {
  alert("index = " + index);
}
alert('No more instances of lowercase "L" in the string.');

Here is an example which proves that searching for a substring which isn’t in the string will immediately return -1:

var str = "John Resig really knows his stuff!";
var iter = str.indexOfIter("?");
alert('A "?" was ' + (iter() ? "not " : "") + "found in:\n" + str);

Finally, here is an example which proves that doing a search for the empty string will progressively iterate through the entire string:

var index, str = "word", iter = str.indexOfIter("");
while((index = iter()) != -1) {
  alert("index = " + index);
}
alert('No more instances of the empty string.');

In conclusion, the question is, do we need JavaScript 1.7 to make good iterators? I don’t think so. On the other hand, I eagerly await the time when most people are using the major browsers (discounting Microsoft Internet Explorer ;)) which include at least JavaScript 1.7. Until then, the JavaScript guys out there will have to continue coming up with interesting solutions, which is pretty fun too. 8)


1 Comment

Chris West's Blog » JavaScript – indexOf Iterator Via A Generator · October 20, 2011 at 6:46 PM

[…] Yesterday, I posted about creating String.prototype.indexOfIter() which basically returned a function which would act as an iterator function, indicating the indices of the specified substring. What I neglected to include was how to write this solution using JavaScript 1.7 in FireFox. Today, I bring to you the equivalent using a generator function. Checkout the code and example of JSBin.com by clicking here. […]

Leave a Reply

Your email address will not be published. Required fields are marked *