Skip to content

Instantly share code, notes, and snippets.

@dunstontc
Last active June 4, 2017 19:22
Show Gist options
  • Save dunstontc/a5b5796a4ad69ca318438bd2af81abc7 to your computer and use it in GitHub Desktop.
Save dunstontc/a5b5796a4ad69ca318438bd2af81abc7 to your computer and use it in GitHub Desktop.
/* ID Generator:
*
* You can use an infinite while in a generator function to create
* a function that will generate a new ID every time next() is called on it.
* In this case the infinite loop is not dangerous
* because it will only execute once with calls to next().
*
*/
function* idGen(){
let i = 0;
while (true) {
yield ++i;
}
}
const myIdGen = idGen();
console.log(myIdGen.next().value); // 1
console.log(myIdGen.next().value); // 2
console.log(myIdGen.next().value); // 3
console.log(myIdGen.next().value); // 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment