Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between "new" and directly invoking a generator function?

I know the difference between "new" and directly invoking a normal function.

But how about the case for the generator function?

e.g:

function *counter(){
    let n = 0;
    while (n < 2) {
        yield n++;
    }
    return 10;
}

var countIter1 = new counter();
var countIter2 = counter();

seems they're the same?

like image 483
kelviN Avatar asked Mar 24 '14 17:03

kelviN


People also ask

Which is the correct way to declare a generator function?

The function* declaration ( function keyword followed by an asterisk) defines a generator function, which returns a Generator object.

Which function is used to call generator?

Generator functions are defined using the * asterisk either immediately after the function keyword or right before the function name. The below example creates an infinite number of natural numbers, which can be used when needed. We can use the yield* to call another generator from within a generator.

How do you end a generator function?

To finish the execution of the generator function, we can use the return statement. Returned value will be used to set the value property of the object returned by the generator.


1 Answers

Generators allow you to define an iterative algorithm by writing a single function which can maintain its own state.A generator is a special type of function that works as a factory for iterators. A function becomes a generator if it contains one or more yield expressions.When a generator function is called the body of the function does not execute straight away; instead, it returns a generator-iterator object. Each call to the generator-iterator's next() method will execute the body of the function up to the next yield expression and return its result. When either the end of the function or a return statement is reached, a StopIteration exception is thrown. A generator function can be used directly as the iterator method of a class, greatly reducing the amount of code needed to create custom iterators.

 function Range(low, high){
      this.low = low;
      this.high = high;
    }
    Range.prototype.__iterator__ = function(){
      for (var i = this.low; i <= this.high; i++)
        yield i;
    };
    var range = new Range(3, 5);
    for (var i in range)
      print(i); // prints 3, then 4, then 5 in sequence

Not all generators terminate; it is possible to create a generator that represents an infinite sequence.

like image 193
user-S Avatar answered Sep 18 '22 08:09

user-S