javascriptgeneratores6-generator

Javascript Generator: how to get an object as parameter to generate another object?


I'm trying to get a "template" object as input to a generator, in order to get other objects. I would be able to change the template just before each generation.

It's almost working as expected, but I'm having the following issue. I just put together a simplified example of the problem here:

function* generator () {
    while(true) {
        let obj = yield
        yield {
            name: obj.name
        }
    }
}
let gen = generator()

let obj = {
    name: 'name'
}
gen.next(obj)

obj.name = 'test'
for(let i=3; i--; ) {
    let item = gen.next(obj).value
    console.log(JSON.stringify(item))
}

I was expecting to get as a result:

{name: test}
{name: test}
{name: test}

However, I'm getting:

{name: test}
undefined
{name: test}

Solution

  • Cause you yield twice, one time yielding nothing. Yield just once:

     let obj = {};
     while(true) {
        obj = yield { name: obj.name };
     }