Reputation: 1767
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
Reputation: 18734
Here are the things I can tell are wrong:
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
Reputation: 66304
If you..
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
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