This has been mentioned a few times earlier this year, but i only just realized how useful these “Generators” are.
One of my pet peeves about typical JavaScript is that it is more or less impossible to save and restore the state of a function. I have found this to be quite useful in languages such as Ruby in which it is practically used everywhere though the use of the “yield” keyword. For example:
def my_funky_iterator
yield 1
yield 2
yield 4
yield 8
end
my_funky_iterator do |yielded_item|
puts yielded_item
end
Which would print
1
2
4
8
So in essence, the “yield” keyword turns a function into an iterator. Each time the “yield” is invoked, Ruby passes control to the supplied block which then handles the yielded value – in this example, it just prints it. Finally, it returns control back to the function which called the yield.
This is where JavaScript 1.7 ’s “Generators” come into play. It is essentially the implementation of the “yield” keyword in JavaScript, so with a little tweaking we can rewrite the above code in JavaScript:
function myfunkyIterator()
{
yield 1;
yield 2;
yield 4;
yield 8;
}
var funky_iterator_instance = myfunkyIterator();
var yielded_item = null;
while (yielded_item = funky_iterator_instance.next())
{
alert(yielded_item);
}
my_funky_iterator_instance.close();
Which you can try out by clicking on one of these nice buttons. The former iterates over all the values, whilst the latter only iterates to the next value.
Click me!
Click me 2!
var glob_iterator_instance = null; function myfunkyIterator() { yield 1; yield 2; yield 4; yield 8; } function myfunkyIteratorCaller() { var funky_iterator_instance = myfunkyIterator(); var yielded_item = null; while (yielded_item = funky_iterator_instance.next()) { alert(yielded_item); } my_funky_iterator_instance.close(); } function myfunkyreentrantCaller() { if (glob_iterator_instance == null) { glob_iterator_instance = myfunkyIterator(); } var yielded_item = glob_iterator_instance.next(); if (yielded_item) { alert(yielded_item); } else { glob_iterator_instance.close(); glob_iterator_instance = null; } }
I can see Generators being quite useful in scripting, particularly with animations.
Sadly, the only web browser which supports generators is FireFox 2. Though it is interesting to note that there is a Mozilla project called ScreamingMonkey which might allow Internet Explorer to run next gen JavaScript 2.0 code, so i guess there is hope yet.

Add New Comment
Thanks. Your comment is awaiting approval by a moderator.
Do you already have an account? Log in and claim this comment.
Add New Comment
Trackbacks
(Trackback URL)