In: Computer Science
class Iterator { constructor(arr){ this[Symbol.iterator] = () => this this._array = arr this.index = 0 } next(){ const done = this.index >= this._array.length const value = this._array[this.index++] return {done, value} } //YOUR WORK HERE } const arr = ["a","b","c","d","e"] const it = new Iterator(arr) it.forEach(item => console.log(item)) console.log("Let's try that again...") it.forEach(item => console.log(item)) //produces no output console.log("Extra credit: with indices...") const it2 = new Iterator(arr) it2.forEach((item, index) => console.log(item, index)) /* a b c d e Let's try that again... Extra credit: with indices... a 0 b 1 c 2 d 3 e 4 */
Code in Javascript
class Iterator {
constructor(arr){
this[Symbol.iterator] = () => this
this._array = arr
this.index = 0
}
next(){
const done = this.index >= this._array.length
const value = this._array[this.index++]
return {done, value}
}
forEach(func){
while(this.index<this._array.length){
const index = this.index;
const item = this._array[index];
func.call(this,item, index);
this.index++;
}
}
}
const arr = ["a","b","c","d","e"]
const it = new Iterator(arr)
it.forEach(item => console.log(item))
console.log("Let's try that again...")
it.forEach(item => console.log(item))
// produces no output
console.log("Extra credit: with indices...")
const it2 = new Iterator(arr)
it2.forEach((item, index) => console.log(item, index))
Sample Output
Explanation
We are passing a function inside the forEach function and for every value from current index to the end we are calling this passed function. Let me know in the comments if you have any confusion.