Node.js Iterator interface

iterator, javascript, node.js

Solution

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

Anyway, Node.js now has better harmony support since the question was asked. Here's an updated code sample which works out of the box on Node 4.2. The __iterator__ name was changed to Symbol.iterator, and the StopIteration exception isn't 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);
}

Problem

I am reading the MDN guide on Iterators and generators and I implemented 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 it should have returned : ``` 3 4 5 ``` Is it possible to implement this as expected in Node.js? Note: I am using `node --harmony myscript.js`. ** Edit ** I should also note that I am aware that `__iterator__` is a Mozilla-feature only. I'd like to know what's the equivalent in Node.js. Or what's the next best thing. Also, I'd like to not use a generator for this as I want the iteration to be free of 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 alternatives?

Original source