Lu4
Lu4

Reputation: 15032

How to create iterable `function *() {}` via `new Function()` interface in ES6

The title stand for itself, there's a new iterable function interface in ES6, and the question is fairly simple, how to create an iterable function that supports yield via new Function(...) interface,

P.S.

I've tried doing

var f = function *() {
  yield 1;
  yield 2;
  yield 3;
}

in Google Chrome console, and then doing f.toString() it gave the following output:

function* () {
  yield 1;
  yield 2;
  yield 3;
}

not sure however how to deal with it... when I try the following:

var g = new Function(`
  yield 1;
  yield 2;
  yield 3;
`);

It produces error: Uncaught SyntaxError: Unexpected number

Thank you in advance!

Upvotes: 0

Views: 62

Answers (1)

Azamantes
Azamantes

Reputation: 1461

You might want to be interested in this:

var GeneratorFunction = Object.getPrototypeOf(function*(){}).constructor
var g = new GeneratorFunction("a", "yield a * 2");
var iterator = g(10);
console.log(iterator.next().value); // 20

This is an example from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction

It makes basically what you want, looks like you were just looking at the wrong constructor.

Upvotes: 4

Related Questions