Stepan Loginov
Stepan Loginov

Reputation: 1767

Get single yield value from iterator/generator

I need entity that return incrementing integer after each call.

For example I have code.

var id = 0; //global variable =(

function foo() {
   ....
   console.log("Your unique ID is " + id++);
   ....
}

and it works fine. But I want to use generators for this work.

Something like:

function* getId() {
   var id = 0;
   while (true) {
       yield id++;
   }
}

 function foo() {
   ....
   console.log("Your unique ID is " + getId());
   ....
}

But result is only empty figure quotes. What i missed? Maybe using generators is a bad idea for this kind of generation?

Upvotes: 2

Views: 1616

Answers (3)

maioman
maioman

Reputation: 18734

Here are the things I can tell are wrong:

  • you're resetting the id value on every function call.
  • for the generator to output the value of next iteration you need to generate the iterator, then you can access its next().value

Here's an example:

function* getId() {
 var id = 0;
    while (true) {
      yield id++;
    };
}

var itId = getId();

function foo() {
  console.log("Your unique ID is " + itId.next().value);
}

foo()
foo()

Upvotes: 3

Paul S.
Paul S.

Reputation: 66304

If you..

  • don't want to pollute your namespace
  • want short code

Then maybe an IIFE closing over the incremented variable will serve you better than a function* in this case

var getId = (function () {
    var i = 0;
    return () => i++;
}());

getId(); // 0
getId(); // 1
getId(); // 2

Upvotes: 1

Bergi
Bergi

Reputation: 664297

Your getId is a generator function that creates a generator, instead of advancing one and getting its values.
You should do something like

function* IdGenerator() {
    var i = 0;
    while (true) {
        yield i++;
    }
}
IdGenerator.prototype.get = function() {
    return this.next().value;
};

var ids = IdGenerator();
function foo() {
    …
    console.log("Your unique ID is " + ids.get());
    …
}

Upvotes: 9

Related Questions