Skip to content

Instantly share code, notes, and snippets.

@ungarson
Created July 13, 2019 08:52
Show Gist options
  • Save ungarson/80060f10b428a3200f6913bc2b535a1f to your computer and use it in GitHub Desktop.
Save ungarson/80060f10b428a3200f6913bc2b535a1f to your computer and use it in GitHub Desktop.
Passing an argument to a generator function in example of generating IDs
export default function* idGeneration(start = 0) {
while(true) {
const newID = yield start++;
if (typeof newID !== 'undefined') {
start = newID;
yield start++;
}
}
}
// Example of usage
// const idGenerator = idGeneration();
// console.log(idGenerator.next().value); // 0
// console.log(idGenerator.next().value); // 1
// console.log(idGenerator.next().value); // 2
// console.log(idGenerator.next(5).value); // 5
// console.log(idGenerator.next().value); // 6
// console.log(idGenerator.next().value); // 7
// console.log(idGenerator.next(100).value); // 100
// console.log(idGenerator.next().value); // 101
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment