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

134 Views Asked by At

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}
1

There are 1 best solutions below

1
On BEST ANSWER

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

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