How would I make an iterator out of an ES6 class in the same manner as JS1.7 SomeClass.prototype.__iterator__ = function() {...}
syntax?
[EDIT 16:00]
The following works:
class SomeClass { constructor() { } *[Symbol.iterator]() { yield '1'; yield '2'; } //*generator() { //} } an_instance = new SomeClass(); for (let v of an_instance) { console.log(v); }
WebStorm flags *[Symbol.iterator]()
with a 'function name expected' warning directly following the asterix, but otherwise this compiles and runs fine with Traceur. (Note WebStorm does not generate any errors for *generator()
.)
The iterable protocol In order to be iterable, an object must implement the @@iterator method, meaning that the object (or one of the objects up its prototype chain) must have a property with a @@iterator key which is available via constant Symbol.
Iterator is an object which allows us to access a collection of objects one at a time. The following built-in types are by default iterable − String. Array. Map.
An iterator can be created from an iterable by using the function iter(). Thus, when we pass this tuple to an iter() function, we will get an iterator. Actually, this is possible because the class of an object has a method __iter__, which returns an iterator.
entries. In order to make objects iterable, we need to first understand how iteration work in JavaScript. When an iterable data structure, like an array, string, array of arrays, and so on, are iterated over with the for/of loop, a special method within their definition is invoked, the [Symbol. iterator]() method.
You need to specify Symbol.iterator
property for SomeClass
which returns iterator for class instances. Iterator must have next()
method, witch in turn returns object with done
and value
fields. Simplified example:
function SomeClass() { this._data = [1,2,3,4]; } SomeClass.prototype[Symbol.iterator] = function() { var index = 0; var data = this._data; return { next: function() { return { value: data[++index], done: !(index in data) } } }; };
Or using ES6 classes and arrow functions:
class SomeClass { constructor() { this._data = [1,2,3,4]; } [Symbol.iterator]() { var index = -1; var data = this._data; return { next: () => ({ value: data[++index], done: !(index in data) }) }; }; }
And usage:
var obj = new SomeClass(); for (var i of obj) { console.log(i) }
In your updated question you realized class iterator through generator function. You can do so, but you must understand that iterator COULD NOT BE a generator. Actually iterator in es6 is any object that has specific next()
method
Define a suitable iterator method. For example:
class C { constructor() { this.a = [] } add(x) { this.a.push(x) } [Symbol.iterator]() { return this.a.values() } }
Edit: Sample use:
let c = new C c.add(1); c.add(2) for (let i of c) console.log(i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With