Node.js Iterator Interface

I am reading the MDN manual on iterators and generators , and I have completed the following example:

function Range(low, high){ this.low = low; this.high = high; } Range.prototype.__iterator__ = function(){ return new RangeIterator(this); }; function RangeIterator(range){ this.range = range; this.current = this.range.low; } RangeIterator.prototype.next = function(){ if (this.current > this.range.high) throw StopIteration; else return this.current++; }; var range = new Range(3, 5); for (var i in range) { console.log(i); } 

But I get this:

 low high __iterator__ 

Where he was supposed to return:

 3 4 5 

Is it possible to implement this as expected in Node.js?

Note: I am using node --harmony myscript.js .

** Change **

It should also be noted that I know that __iterator__ is only a Mozilla function . I would like to know what is equivalent in Node.js. Or what's the best.

Also, I would not want to use a generator for this, since I want the iteration to not contain any conditional tests.

My conclusion is that the only equivalent is

 Range.prototype.each = function (cb) { for (var i = this.low; i <= this.high; i++) { cb(i); } }; //... range.each(function (i) { console.log(i); }); 

Are there any alternatives?

+6
source share
2 answers

I think your code had an error where you wrote for (var i in range) instead of for (var i of range) . The in keyword prints out the properties of the object you want to use of to actually get the iterator values.

In any case, Node.js now has better harmony support, as the question is asked. Here's an updated sample code that works out of the box on Node 4.2. The name __iterator__ has been changed to Symbol.iterator, and the StopIteration exception is not used.

 "use strict"; function Range(low, high){ this.low = low; this.high = high; } Range.prototype[Symbol.iterator] = function(){ return new RangeIterator(this); }; function RangeIterator(range){ this.range = range; this.current = this.range.low; } RangeIterator.prototype.next = function(){ let result = {done: this.current > this.range.high, value: this.current}; this.current++; return result; }; var range = new Range(3, 5); for (var i of range) { console.log(i); } 
+4
source

Yes it is.

Generators and iterators are part of ECMAScript 6 / JavaScript 1.7. Node supports them, but you need to activate them when you run the script.

For instance:

 node --harmony_generators --harmony_iteration your_script.js 

Take a look at this blog post for more information.

+1
source

All Articles