Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easier way to iterate over generator? [duplicate]

Is there an easier way (than the one I am using) to iterate over a generator? Some sort of best practice pattern or common wrapper?

In C# I'd usually have something as simple as:

public class Program {
    private static IEnumerable<int> numbers(int max) {
        int n = 0;
        while (n < max) {
            yield return n++;
        }
    }

    public static void Main() {
        foreach (var n in numbers(10)) {
            Console.WriteLine(n);
        }
    }
}

Trying the same in JavaScript this is the best I could come up with:

function* numbers(max) {
  var n = 0;
  while (n < max) {
    yield n++;
  }
}

var n;
var numbers = numbers(10);
while (!(n = numbers.next()).done) {
  console.log(n.value);
}

Though I would have expected something simple as this ...

function* numbers(max) {
  let n = 0;
  while (counter < max) {
    yield n++;
  }
}

for (let n in numbers(10)) {
  console.log(n);
}

... which is much more readable and concise, but apparently it's not as easy as that yet? I've tried node 0.12.7 with --harmony flag and also node 4.0.0 rc1. Is there something else I have to do to enable this feature (including the usage of let while I am at it) if this is even available yet?

like image 744
Num Lock Avatar asked Sep 07 '15 10:09

Num Lock


People also ask

How many times can you iterate through a generator?

This is because generators, like all iterators, can be exhausted. Unless your generator is infinite, you can iterate through it one time only. Once all values have been evaluated, iteration will stop and the for loop will exit.

How do you iterate over a generator in Python?

You need to call next() or loop through the generator object to access the values produced by the generator expression. When there isn't the next value in the generator object, a StopIteration exception is thrown. A for loop can be used to iterate the generator object.

Is a for loop a generator?

One final thing to note is that we can use generators with for loops directly. This is because a for loop takes an iterator and iterates over it using next() function. It automatically ends when StopIteration is raised. Check here to know how a for loop is actually implemented in Python.

What is JavaScript generator?

In ECMAScript 2015, generators were introduced to the JavaScript language. A generator is a process that can be paused and resumed and can yield multiple values. A generator in JavaScript consists of a generator function, which returns an iterable Generator object.


1 Answers

You need to use the for..of syntax for generators. This creates a loop for iterable objects.

function* numbers(max) {
  let n = 0;
  while (n < max) {
    yield n++;
  }
}

Using it:

for (let n of numbers(10)) {
  console.log(n); //0123456789
}

Documentation

like image 106
Ben Fortune Avatar answered Oct 02 '22 11:10

Ben Fortune