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?
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?
Share Improve this question edited May 8, 2016 at 22:38 Bergi 666k161 gold badges1k silver badges1.5k bronze badges asked May 8, 2016 at 21:42 Stepan LoginovStepan Loginov 1,7675 gold badges24 silver badges55 bronze badges3 Answers
Reset to default 9Your 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());
…
}
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()
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