Reputation: 95
How can I compose a producer generator that gets values externally with another generator? If producer
yields a value within the generator then it works, but when I send a value with next
I get undefined
. Is there a way to do this?
function* producer() {
while (true) {
yield // want to send values here
}
}
function* take(n, gen) {
var i = 0
for (var x of gen) {
if (i <= n) {
yield x // want the value sent to the producer
i += 1
} else {
break
}
}
}
var prod = producer()
var res = take(5, prod)
// How can I send values to the producer
// and make the result yield those values?
res.next() // init
console.log(res.next(1)) // {value: undefined, done: false}
console.log(res.next(2)) // {value: undefined, done: false}
// ...
// I want to get
// {value: 1, done: false}
// {value: 2, done: false}
// ...
Upvotes: 1
Views: 62
Reputation: 35134
To get a value which is sent to next()
, you should use the result that is returned by yield. I am not quite sure what your end goal is, but here is your modified example:
let producer = function*() {
var nextResult = undefined;
while(true) {
nextResult = yield nextResult;
console.log("produce " + nextResult);
}
}
let take = function*(number, items) {
var count = 0;
var item = undefined;
while (count <= number) {
items.next(item);
item = yield item;
console.log("take " + item);
count += 1;
}
}
var res = take(2, producer())
res.next() // init
console.log('result ' + res.next(3).value)
console.log('result ' + res.next(2).value)
This outputs:
take 3
produce 3
result 3
take 2
produce 2
result 2
Upvotes: 1