The following code refers to Firefox-specific JavaScript 1.7 implementation with Array comprehensions and iterators/generators. Note that as of this post’s writing, ‘Iterator’, ‘yield’, and array comprehensions are not yet supported in Webkit browsers (Chrome, Safari) and seem to only work on Firefox’s JavaScript engine (Google, liberateme).
NB: ECMAScript Harmony may bring about new changes to syntax and may make this post obsolete
var myobject = {'foo':5,'bar':10};
var myarray = [10,20,30];
for (var i in it) {
console.log(i);
}
Code:
JavaScript:
//if var it = Iterator(myobject);
['foo',5]
['bar',10]
//if var it = Iterator(myarray);
[0,10]
[1,20]
[2,30]
It seems like JS 1.7 Iterators ALWAYS return a ‘key’ and a ‘value’ (whether the key is an actual object key or the index of an array. Contrast this to Python, where Iterators are smart enough to return only 1 value if it is an array.
Python:
#if it = iter(myobject);
[foo,5]
[bar,10]
#if it = iter(myarray);
10,
20,
30
So the question is, how come Iterator() and iter() don’t do the same thing when I am trying to port Python-to-JavaScript functions?
Answer:
For the sake of porting code from Python Functions/Libraries to JavaScript, it is a bit frustrating to presume that Iterator() and iter() do the same thing, only to realize that (they are slightly different and results in the developer having to sometimes roll their own Iterator/Generator functions (using ‘yield’)*.
for example, let’s say we wanted to roll the python’s items() function that is native to dict objects.
items() works just fine when passing it the myobject JavaScript Object (granted, I am using nested arrays rather than tuples).
However, when constructing an iterator for items(myobject), we are actually iterating over a list so we want to make a custom generator that only yields the 2nd index to reproduce Python’s functionality:
Notice that there is actually a bit of redundancy here. Notice that
So in the end, just be careful of what you are iterating over and see if you can speed up your call by avoiding calling functions that end up being each others’ inverse.
I hope that all this is factually accurate – please correct me if I am wrong.