Ben Aston
Ben Aston

Reputation: 55729

How can I get the following generator to work?

As an experiment I want to create a generator that yields some integers with the following approximate design.

Can I get this to work (i.e. yielding from an inner function)?

function* numbers() { 
  [...Array(31)].forEach((_,i)=> {
      yield i; // Invalid syntax - how can this be changed?
  });
}

var generator = numbers();

for(var i of generator) {
    console.log(i); // I want 0 1 2 3 4 5 6 7... to 30 to be printed
}

Upvotes: 0

Views: 45

Answers (1)

Rafael Z.
Rafael Z.

Reputation: 1162

function* numbers() { 
  yield* Object.keys([...Array(31)])
}

var generator = numbers()

for(var i of generator) {
    console.log(i)
}

Upvotes: 2

Related Questions