Problems in a class generating a loop with iterators in javascript

1

I am creating a class to practice iterators in javascript. This is my code:

class iterador{
    constructor(...n){
    this.n = n
    this.lon = n.length
    this.indice = 0
    this.next = function next(){
        return this.indice < this.lon ? {value:this.n[this.indice++], done: false} : {done:true}
        }
    }
    loop(){
        let l = {}
        l[Symbol.iterator] = this.next
        console.log(l)
        let i = 0
        for(let value of l){
            console.log(value)
            i++
            if(i>this.lon) break
        }
    }
}
const ite = new iterador(1,2,3,4,5,6,7,8,9,10)
ite.next().value // 1

ite.loop() // no funciona 

The idea is that the loop () method gives me a tour of all the parameters that I sent when creating the new object ite, some advice?

    
asked by Victor Lozada 01.06.2018 в 02:09
source

1 answer

0

First solution, spending your iterator:

loop(){
  var item
  while (!(item = this.next()).done) console.log(item.value)
  console.log('done')
}

In your example: ite.loop() will log 2,3,4,5,6,7,8,9,10 'done', as you called ite.next() and once.

What you need is something to restart your iterator if you need it

Second solution, without moving your index / spend your iterator:

loop(){
    this.n.forEach((item) => { console.log(item) })
}

In your example: ite.loop() logs 1,2,3,4,5,6,7,8,9,10, and if you call later ite.next().value // 2

    
answered by 02.06.2018 в 14:22