Let's understand iteration in js by making Range
class.
class Range {
constructor(start,end) {
this.start = start
this.end = end
}
[Symbol.iterator]() {
let i = this.start
return {
next: () => {
if (i > this.end) {
return {value: undefined, done: true}
}
return {value: i++, done: false}
}
}
}
}
const r = new Range(1,10)
for (let i of r) {
console.log(i)
}
console.log("finished")
Range
class here is an iterable because it follows the iterable protocol. It's Symbol.iterator
method returns an object which follows the iterator protocol.
An object is said to be following the iterator protocol when it implements the next
method. It's next method should return an object which conforms to the IteratorResult
interface.