Stepan Loginov Stepan Loginov - 5 months ago 26
Node.js Question

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?

Answer

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());
    …
}