Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for wrapping generators #45

Open
ruipin opened this issue Jul 23, 2021 · 0 comments
Open

Add support for wrapping generators #45

ruipin opened this issue Jul 23, 2021 · 0 comments
Labels
enhancement New feature or request

Comments

@ruipin
Copy link
Owner

ruipin commented Jul 23, 2021

Because generator functions are synctactic sugar around a Generator factory, trying to wrap a generator the naive way will trigger a libWrapper exception:

game.generatorFn = function*(...args) {
  yield args[0];
  yield args[1];
  yield args[2];
};

libWrapper.register('package_id', 'game.generatorFn',  function*(wrapped, ...args) {
  const gen = wrapped(...args);
  yield gen.next().value+1;
  yield gen.next().value+1;
  yield gen.next().value+1;
}, "WRAPPER");

console.log(game.generatorFn(1).next());
// <- The wrapper for 'game.generatorFn' registered by module 'package_id' with type WRAPPER did not chain the call to the next wrapper, which breaks a libWrapper API requirement. This wrapper will be unregistered.

A workaround is to divide the wrapper into two parts, a factory, and a generator:

game.generatorFn = function*(...args) {
  yield args[0];
  yield args[1];
  yield args[2];
};

function* generatorFn_wrapped(wrapped, ...args) {
  yield wrapped.next().value+1;
  yield wrapped.next().value+1;
  yield wrapped.next().value+1;
}

libWrapper.register('package_id', 'game.generatorFn',  function(wrapped, ...args) {
  return generatorFn_wrapped(wrapped(...args), ...args);
}, "WRAPPER");

console.log(game.generatorFn(1,2,3).next().value);
// <- 2

It might be a good idea to have libWrapper do this automatically when it detects the wrapper function is a generator. When libWrapper.register detects that the wrapper function is a generator, it should automatically create a corresponding factory, and register that instead, similar to above.

To detect whether a function is a generator, the following StackOverflow thread is useful:
https://stackoverflow.com/questions/21559365/how-to-identify-an-es6-generator

@ruipin ruipin added the enhancement New feature or request label Jul 23, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant