简体   繁体   中英

Best practice for passing through generator function in JS

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 :

  1. How do I passthrough a return in addition to yield ?
  2. Is there a better and more clean way to implement it?
  1. How do I passthrough a return in addition to yield ?
* generate() {
    return yield* this.service.generate();
}
  1. Is there a better and more clean way to implement it?
generate() {
    return this.service.generate();
}
 #service;
this.#service = …
return this.#service.generate();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM