I built my code based on insights from this code:
https://github.com/davidflanagan/jstdg7/blob/master/ch12/Range.js
class SayHi {
constructor (hi, repeat) {
this.hi = hi;
this.repeat = repeat;
}
[Symbol.iterator]() {
let next = 1;
let last = this.repeat;
let hi = this.hi;
return {
next() {
if (next<=last) {
let now = next;
next++;
return { value: hi+now };
}
else {
return { done: true };
}
},
// What's the use of this??
[Symbol.iterator]() {
return this;
}
};
}
}
let sayHi = new SayHi("HI", 3);
for(let x of sayHi) console.log(x);
I do not understand how this line of code works from the context of the whole program, because the program works without this code:
[Symbol.iterator]() { return this; }
How does it work? Why are we returning 2 functions for the outer Symbol.iterator? How do we invoke each of the functions?
This is a relatively simple concept, something that I have recently learned myself. If you have a normal iterator object that rsturns an object without the [Symbol.iterator] then this would throw an error:
let data = [...iterator];
With this line, not only does the program not throw an error, but these two methods generate the exact same thing:
let data1 = [...sayHiInstance];
let data2 = [...sayHiInstance[Symbol.iterator]()];