Generators ES6
JavaScript
const range = {
from: 1,
to: 5,
/* [Symbol.iterator]() {
return {
current: this.from,
last: this.to,
next() {
if (this.current <= this.last) {
return {done: false, value: this.current++}
}
else {
return {done: true, value: undefined}
}
}
}
} */
*[Symbol.iterator]() { // a shorthand for [Symbol.iterator]: function*()
for(let item = this.from; item <= this.to; item++) {
yield item;
}
}
}
console.log([...range]);