Reputation: 10371
I am trying to figure out the best practice of passing a generator (including yield) function through another function as is.
In other words, I am looking for a better way to achieve the following.
Let's say that I have class ServiceA
and ServiceB
, that own the same method generate
, that generates some sequences:
class ServiceA extends ServiceBase {
// ...
* generate() {
const length = Math.round(Math.rand() * 100);
for (let i=0; i<length; i++)
yield i;
return -1;
}
// ...
}
class ServiceB extends ServiceBase {
// ...
* generate() {
const length = Math.round(Math.rand() * 100) + 100;
for (let i=100; i<length; i++)
yield i;
return 13;
}
// ...
}
Now, I have a wrapper class ServiceName
that uses class ServiceA
or ServiceB
, but also, passing through the generate
method from these classes:
class ServiceManager {
#service;
constructor(serviceName) {
// The following require will return ServiceA or ServiceB instance
this.#service = require('./service/' + serviceName);
}
* generate() {
for ( let i of this.#service.generate() )
yield i;
}
// ...
}
And extension is not an option, as this is a design pattern I need.
Two questions regarding the generate
method within class ServiceManager
:
return
in addition to yield
?Upvotes: 0
Views: 97
Reputation: 225005
- How do I passthrough a
return
in addition toyield
?
* generate() {
return yield* this.service.generate();
}
- Is there a better and more clean way to implement it?
generate() {
return this.service.generate();
}
#service;
this.#service = …
return this.#service.generate();
Upvotes: 1